[Practice] binary cattle off net balance check

Reference: Learning from the big brother

topic

Implement a function, checks whether the balanced binary tree, the balance is defined as follows, for any node in the tree, the height difference between the two sub-tree which does not exceed 1.

Given a pointer pointing to the tree root TreeNode * root, please return a bool, on behalf of the tree is balanced.

analysis

1. The height difference between the calculated left subtree and right subtree is greater than a false
2. How to get?
Recursive obtained, if the node is empty then the depth of 0, which is also recursive export, if not empty then recursively the left subtree and the right subtree.
Note: The final height of the binary tree is the height of left and right subtrees taken high plus 1

Code:

import java.util.*;

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}*/
public class Balance {
    public boolean isBalance(TreeNode root) {
        // write code here
        if(root==null){
            return true;
        }
        int left = getTreeHeight(root.left);
        int right = getTreeHeight(root.right);
        return Math.abs(left - right) <= 1;
    }

    public static int getTreeHeight(TreeNode root){
        if(root==null){
            return 0;
        }
        //这里为什么加1?,因为root为null时返回的是0,我们假设只有三个节点的完全二叉树
        //那是不是最后的结果就是根节点的左孩子0+0+1,根节点的右孩子0+0+1,最后1和1取大的再加1,不就是2嘛
        return Math.max(getTreeHeight(root.left),getTreeHeight(root.right))+1;
    }
}
Published 57 original articles · won praise 11 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_42419462/article/details/103340276