Cattle off net - balanced binary tree to prove safety office-

Title: Enter a binary tree, the binary tree is determined whether a balanced binary tree.
Solution a:
ideas: the use of a function of the depth questions binary tree, each node of the comparison to a depth of about. However, this method requires repeated a plurality of times to traverse the nodes, such that the time efficiency is not high.

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot == nullptr)
            return true;
        int left = TreeDepth(pRoot->left);
        int right =TreeDepth(pRoot->right);
        int diff = abs(left-right);
        if (diff >1)
            return false;
        return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
    }
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot == nullptr)
            return 0;
        return 1+max(TreeDepth(pRoot->left),TreeDepth(pRoot->right));
    }
};

Solution two:
the mind: if the subtree is not a balanced binary tree, a depth directly returns -1

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if (pRoot==nullptr)
            return true;
        return TreeDeep(pRoot)!=-1;
        
    }
    int TreeDeep(TreeNode* pRoot)
    {
        if (pRoot==nullptr)
            return 0;
        int left = TreeDeep(pRoot->left);
        if (left==-1)
            return -1;
        int right =TreeDeep(pRoot->right);
        if (right==-1)
            return -1;
        int diff = abs(left-right);
        return diff>1?-1:max(1+left,1+right);
    }
};

Guess you like

Origin blog.csdn.net/qq_43387999/article/details/91128655