文章目录
  1. 1. Balanced Binary Tree
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题

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。然后递归下去判断。

解题

c++版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 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=height(root->left);
int right=height(root->right);
if(left-right<=1 && left-right>=-1)
return isBalanced(root->left)&&isBalanced(root->right);
else
return false;
}

int height(TreeNode* root){
if(!root)
return 0;
return 1+max(height(root->left),height(root->right));
}
};

python版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Definition for a  binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
if not root:
return True
rightH=self.height(root.right)
leftH=self.height(root.left)
if leftH-rightH<=1 and leftH-rightH>=-1:
return self.isBalanced(root.right) and self.isBalanced(root.left)
else:
return False

def height(self,root):
if not root:
return 0
else:
if not root.right:
return self.height(root.left)+1
elif not root.left:
return self.height(root.right)+1
else:
l = self.height(root.left)
r = self.height(root.right)
if l<r:
return r+1
else:
return l+1

文章目录
  1. 1. Balanced Binary Tree
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题