leetcode-110-Balanced-Binary-Tree

描述


Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

分析


判断一棵树是不是平衡二叉树。平衡二叉树的定义是:它是空树,或者,左右两个子树的高度差不超过1而且两个子树都是平衡二叉树。按照原理写代码就好写了,如果根节点是null,自然是二叉树,否则,需要满足两个条件,两子树高度差不超过1,并且两子树都是平衡二叉树。

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 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:
int depth(TreeNode* root) {
return root?max(depth(root->left), depth(root->right))+1:0;
}
bool isBalanced(TreeNode* root) {
return root?abs(depth(root->left)-depth(root->right))<=1 && isBalanced(root->left) && isBalanced(root->right) : true;
}
};

解决方案2(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int depth(TreeNode root) {
if(root == null) {
return 0;
}
return Math.max(depth(root.left), depth(root.right)) + 1;
}
public boolean isBalanced(TreeNode root) {
if(root == null) {
return true;
}
return Math.abs(depth(root.left)-depth(root.right))<=1 && isBalanced(root.left) && isBalanced(root.right);
}
}

(OS:果然还是C++简洁一点)

解决方案3(Python)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
return abs(self.depth(root.left)-self.depth(root.right)) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
def depth(self, root):
if root is None:
return 0
return max(self.depth(root.left), self.depth(root.right))+1

相关问题

===
(E) Maximum Depth of Binary Tree

题目来源