leetcode 110. Balanced Binary Tree 判断二叉树是否为平衡二叉树

https://leetcode.com/problems/balanced-binary-tree/

leetcode 110. Balanced Binary Tree 判断二叉树是否为平衡二叉树_第1张图片

1.通过计算每个节点左右子树的深度,自顶向下,判断每个节点是否平衡

这种方法存在大量重复计算,效率较低。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(root==nullptr)return true;
        return verify(root);
    }

    int depth(TreeNode* root){
        if(root==nullptr) return 0;
        int left = 1+depth(root->left);
        int right= 1+depth(root->right);
        return max(left, right);
    }
    
    bool verify(TreeNode* root){
        if(root==nullptr)return true;
        if(depth(root->left)-depth(root->right)>1 || depth(root->left)-depth(root->right)<-1)
            return false;
        return verify(root->left)&&verify(root->right);
    }
};

2.自底向上

采用后序遍历的方式,每个节点只需要被遍历一次。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        int dep;
        return balance(root, dep);
    }
    
    bool balance(TreeNode* root, int& depth){
        if(root==nullptr){
            depth= 0;
            return true;
        }
        
        int left, right;
        if(balance(root->left, left) && balance(root->right, right)){
            depth = 1+max(left, right);
            int dif= left-right;
            if(dif<=1 && dif>=-1)
                return true;
        }
        return false;
    }
};

 

你可能感兴趣的:(leetcode)