题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
}
}
解题思路
这里要知道2个知识点就很好解题:
- 平衡因子: 二叉树上任一结点的左子树深度减去右子树深度的差值。
- 平衡二叉树: 二叉树中,每个结点的平衡因子的绝对值都不大于1
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null){
return true;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
if (Math.abs(left-right)>1){
return false;
}
return true;
}
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return left > right ? left+1 : right+1;
}
}