LeetCode 110. Balanced Binary Tree

原题目:https://leetcode-cn.com/problems/balanced-binary-tree/

 

思路:

平衡的条件为左右深度之差的绝对值<2    and    左孩子平衡    and   右孩子平衡

 

代码:

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(root==NULL) return true;
        return abs(maxDepth(root->left)-maxDepth(root->right))<2 &&
                isBalanced(root->right)&&isBalanced(root->left);
    }
    int maxDepth(TreeNode* root) {
        if(root==NULL) return 0;
        return max(maxDepth(root->left),maxDepth(root->right))+1;
    }
};

 

你可能感兴趣的:(LeetCode,DFS)