Skip to content

Commit b1c1dbc

Browse files
committed
平衡二叉树
1 parent d51850b commit b1c1dbc

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

balanced_binary_tree.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
"""
5+
@param root: The root of binary tree.
6+
@return: True if this Binary tree is Balanced, or false.
7+
"""
8+
def isBalanced(self, root):
9+
# write your code here
10+
if not root:
11+
return True
12+
else:
13+
if abs(self._isBalanced(root.left) - self._isBalanced(root.right)) <= 1:
14+
return self.isBalanced(root.left) and self.isBalanced(root.right)
15+
else:
16+
return False
17+
18+
def _isBalanced(self, root):
19+
if not root:
20+
return 0
21+
return 1 + max(self._isBalanced(root.left), self._isBalanced(root.right))

0 commit comments

Comments
 (0)