Leetcode 110. Balanced Binary Tree
程序员文章站
2024-03-19 19:22:58
...
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
- Version 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) {
return true;
}
int left = getDepth(root->left);
int right = getDepth(root->right);
if(abs(left - right) > 1) {
return false;
}
return isBalanced(root->left) && isBalanced(root->right);
}
private:
int getDepth(TreeNode* root) {
if(!root) {
return 0;
}
return max(getDepth(root->left), getDepth(root->right)) + 1;
}
};
- Version 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) {
return checkBalance(root) != -1;
}
private:
int checkBalance(TreeNode* root) {
if(!root) {
return 0;
}
int left = checkBalance(root->left);
if(left == -1) {
return -1;
}
int right = checkBalance(root->right);
if(right == -1) {
return -1;
}
if(abs(left - right) > 1) {
return -1;
}
return max(left, right) + 1;
}
};
Reference
上一篇: 安装Anaconda
推荐阅读
-
Leetcode 110. Balanced Binary Tree
-
[LeetCode]110. Balanced Binary Tree
-
LeetCode 110. Balanced Binary Tree
-
LeetCode 110. Balanced Binary Tree
-
【LeetCode】Balanced Binary Tree(平衡二叉树)
-
leetcode--minimum-depth-of-binary-tree
-
[Leetcode][python]Minimum Depth of Binary Tree
-
LeetCode:102.Binary Tree Level Order Traversal
-
LeetCode 662 Maximum Width of Binary Tree 二叉树的最大宽度
-
[leetcode]662. Maximum Width of Binary Tree(Python)