39.平衡二叉树(java)

题目描述

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

解题思路

1.判断根结点的左右子树高度差判断是否平衡,然后递归地对左右子树进行判断。

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

2.上面的算法在判断上层结点的时候,会多次重复遍历下层结点,增加了不必要的开销。后续遍历时,遍历到一个节点,其左右子树已经遍历  依次自底向上判断,每个节点只需要遍历一次。

public class Solution {
    public boolean isTrue = true;
    public boolean IsBalanced_Solution(TreeNode root) {
        deep_tree(root);
        return isTrue;
    }
    public int  deep_tree(TreeNode root)
    {
        if(root==null)
            return 0;
        int left = deep_tree(root.left);
        int right = deep_tree(root.right);
        if(Math.abs(left-right)>1)
            isTrue = false;
        return right>left ?right+1:left+1;
    }
}
发布了43 篇原创文章 · 获赞 0 · 访问量 445

猜你喜欢

转载自blog.csdn.net/gaopan1999/article/details/104595525