41. The balanced binary tree

Subject description:

  Enter a root node of a binary tree, the tree is judged not a balanced binary tree

Analysis of ideas:

  Solution 1: height determined around the root of the subtree, if the height difference between left and right subtrees not more than 1, then continue to determine its left subtree is not balanced binary tree, if the left and right subtrees are balanced binary tree, then eventually the tree is balanced binary tree.

  Solution 2: Solution 1 in clearer thinking simply, but a node traversed is repeated a plurality of times, the time efficiency of this idea is not high. We postorder way, traversing each node of a binary tree, then traverse to a node before we had to traverse its left and right subtrees, as long as the record depth in its traversal of each node, we can side Analyzing each node while traversing uneven.

Code:

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

Guess you like

Origin www.cnblogs.com/yjxyy/p/10932559.html