- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbalancedBinaryTree.java
More file actions
Latest commit
33 lines (30 loc) · 948 Bytes
/
Copy pathbalancedBinaryTree.java
File metadata and controls
33 lines (30 loc) · 948 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//判断一个二叉树是否为平衡二叉树
//递归求出左子树和右子树的高度,然后判断其值是否相差1
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
publicclassSolution {
inttreeDepth(TreeNoderoot) {
if(root==null) {
return0;
}
intleftDepth = treeDepth(root.left);
intrightDepth = treeDepth(root.right);
returnMath.max(leftDepth + 1, rightDepth + 1);
}
publicbooleanisBalanced(TreeNoderoot) {
if(root==null||(root.left==null&&root.right==null)) {
returntrue;
}
intleftDep = treeDepth(root.left);
intrightDep = treeDepth(root.right);
inttmp = leftDep - rightDep;
return ((tmp>=-1&&tmp<=1)&&isBalanced(root.left)&&isBalanced(root.right));
}
}