[剑指 offer] JT39---balanced binary tree (top-down or bottom-up?)

Sword Finger Offer Question 39

The topic is as follows

Insert picture description here

Idea and code

Top down

It is to find the maximum depth of the left and right trees from the root node and compare them. Then look for the left and right trees of the subtree,
this sounds like a waste of resources
.

class Solution {
    
    
public:
    int tree_depth(TreeNode *root){
    
    
        if(!root) return 0;
        if((!(root->left))&&(!(root->right))) return 1;
        int deep_left=tree_depth(root->left)+1;
        int deep_right=tree_depth(root->right)+1;
        return (deep_left>deep_right)?deep_left:deep_right;
    }
    bool IsBalanced_Solution(TreeNode* pRoot) {
    
    
        if(!pRoot) return true;
        int ldeep=tree_depth(pRoot->left);
        int rdeep=tree_depth(pRoot->right);
        if(abs(ldeep-rdeep)>1) return false;
        return (IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right));
    }
};

bottom up

The bottom-up approach is better, because the middle is equivalent to pruning!
==Once there is an imbalance between the left and right of the subtree, stop the loss immediately and give the result ==

class Solution {
    
    
public:
    int depth(TreeNode *root){
    
    
        if(root == NULL)return 0;
        int left = depth(root->left);
        if(left == -1)return -1; //如果发现子树不平衡之后就没有必要进行下面的高度的求解了
        int right = depth(root->right);
        if(right == -1)return -1;//如果发现子树不平衡之后就没有必要进行下面的高度的求解了
        if(abs(left - right)>1)//注意这里的判断是子树的左右哦!!!
            return -1;
        else
            return 1+(left > right?left:right);
    }
    bool IsBalanced_Solution(TreeNode* pRoot) {
    
    
        return depth(pRoot) != -1;
    }
};

Guess you like

Origin blog.csdn.net/qq_42136832/article/details/114996630