jovetove / zjianfa.github.io Goto Github PK
View Code? Open in Web Editor NEW人间小事
人间小事
面试题 04.04. 检查平衡性
实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 1。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null)
return true;
// 分别获取左右的高度
int deptL = getDept(root.left);
int deptR = getDept(root.right);
if(Math.abs(deptL - deptR) >1)
return false;
// 遍历每一个节点的情况
return isBalanced(root.left) && isBalanced(root.right);
}
// 获取从某个节点开始的深度
public static int getDept(TreeNode root){
if(root == null) return 0;
return Math.max(getDept(root.left), getDept(root.right)) + 1;
}
}
class Solution {
//定义变量减枝
boolean isBlance = true;
public boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}
getDept(root); // 在获取高度时就判断
return isBlance;
}
public int getDept(TreeNode root){
//如果已经找到不平衡的树枝,不需要递归,直接返回
if(!isBlance) {
return 0;
}
if(root == null) {
return 0;
}
int deptL = getDept(root.left);
int deptR = getDept(root.right);
if(Math.abs(deptL - deptR) > 1) {
isBlance = false; // 减枝
}
return Math.max(deptL,deptR) + 1;
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.