mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0110.平衡二叉树.md
This commit is contained in:
@ -498,6 +498,62 @@ class Solution {
|
|||||||
|
|
||||||
Python:
|
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:
|
||||||
```Go
|
```Go
|
||||||
|
Reference in New Issue
Block a user