[剑指offer] 平衡二叉树

本文首发于我的个人博客:尾尾部落

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

解题思路

定义:平衡二叉查找树,简称平衡二叉树。

  1. 可以是空树。
  2. 假如不是空树,任何一个结点的左子树与右子树都是平衡二叉树,并且高度之差的绝对值不超过1。

遍历每个结点,借助一个获取树深度的递归函数,根据该结点的左右子树高度差判断是否平衡,然后递归地对左右子树进行判断。

参考代码

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null)
            return true;
        return Math.abs(maxDept(root.left) - maxDept(root.right)) <=1 &&
            IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
    }
    public int maxDept(TreeNode root){
        if(root == null)
            return 0;
        return 1 + Math.max(maxDept(root.left), maxDept(root.right));
    }
}

猜你喜欢

转载自blog.csdn.net/weiwei121451070/article/details/81517050
今日推荐