Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 110. 平衡二叉树 #60

Open
Animenzzzz opened this issue Aug 26, 2019 · 0 comments
Open

[LeetCode] 110. 平衡二叉树 #60

Animenzzzz opened this issue Aug 26, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回 true 。

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

返回 false 。

解题思路:空节点也平衡。参考了别人的写法,对于递归还需要多加强才行grandyang/leetcode#110

C++解题:

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        if(abs(depth(root->left) - depth(root->right)) > 1) return false;
        return isBalanced(root->left) && isBalanced(root->right);
    }

    int depth(TreeNode *node){
        if(!node) return 0;
        return 1 + max(depth(node->left),depth(node->right));
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant