题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
知识点:数、递归
- 利用后序遍历:左子树、右子树、根节点,先递归到叶子节点,然后回溯判断条件
- 判断树高的代码:
public int depth(TreeNode root){
if (root == null) return 0;
int lh = depth(root.left);
int rh = depth(root.right);
return Math.max(lh, rh) + 1;
}
- 添加每层的平衡二叉树的判断,如果不满足则返回-1,当得到-1时,跳出递归,返回结果。
- 时间复杂度:O(n)
- 空间复杂度:O(n)
public int dfs(TreeNode root){
if (root == null) return 0;
int lh = dfs(root.left);
if (lh == -1) return -1;
int rh = dfs(root.right);
if (rh == -1) return -1;
int sub = Math.abs(lh - rh);
if (sub > 1) return -1;
return Math.max(lh, rh) + 1;
}
public int depth(TreeNode root){
if (root == null) return 0;
int lh = depth(root.left);
int rh = depth(root.right);
return Math.max(lh, rh) + 1;
}