ACWING72. Balanced binary tree (to prove safety offer)

Input binary tree root node, the tree determination is not a balanced binary tree.

If the depth of the left and right subtrees of any node of a binary tree differs by no more than one point, then it is a balanced binary tree.

note:

Provisions empty tree is a balanced binary tree.
Sample
input: binary [5,7,11, null, null, 12,9 , null, null, null, null] as shown below,
5
/
711
/
129

Output: true

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        if(judge(root,1) == -1) return false;
        return true;
    }

    int judge(TreeNode* root,int dep) {
        int Left = dep,Right = dep;
        if(root -> left) Left = judge(root -> left,dep + 1);
        if(root -> right) Right = judge(root -> right,dep + 1);
        if(!root -> left && !root -> right) return dep;
        if(Left == -1 || Right == -1) return -1;
        if(abs(Left - Right) <= 1) return Left + Right;
        else return -1;
    }
};
Published 844 original articles · won praise 28 · views 40000 +

Guess you like

Origin blog.csdn.net/tomjobs/article/details/104966397