Skip to content

Commit

Permalink
Update 0110.平衡二叉树.md
Browse files Browse the repository at this point in the history
  • Loading branch information
z80160280 authored Jun 6, 2021
1 parent ea6dcc9 commit 6efc66e
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions problems/0110.平衡二叉树.md
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,62 @@ class Solution {

Python:

> 递归法:
```python
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
return True if self.getDepth(root) != -1 else False

#返回以该节点为根节点的二叉树的高度,如果不是二叉搜索树了则返回-1
def getDepth(self, node):
if not node:
return 0
leftDepth = self.getDepth(node.left)
if leftDepth == -1: return -1 #说明左子树已经不是二叉平衡树
rightDepth = self.getDepth(node.right)
if rightDepth == -1: return -1 #说明右子树已经不是二叉平衡树
return -1 if abs(leftDepth - rightDepth)>1 else 1 + max(leftDepth, rightDepth)
```
> 迭代法:
```python
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
st = []
if not root:
return True
st.append(root)
while st:
node = st.pop() #中
if abs(self.getDepth(node.left) - self.getDepth(node.right)) > 1:
return False
if node.right:
st.append(node.right) #右(空节点不入栈)
if node.left:
st.append(node.left) #左(空节点不入栈)
return True
def getDepth(self, cur):
st = []
if cur:
st.append(cur)
depth = 0
result = 0
while st:
node = st.pop()
if node:
st.append(node) #中
st.append(None)
depth += 1
if node.right: st.append(node.right) #右
if node.left: st.append(node.left) #左
else:
node = st.pop()
depth -= 1
result = max(result, depth)
return result
```


Go:
```Go
Expand Down

0 comments on commit 6efc66e

Please sign in to comment.