mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
Merge pull request #1453 from ExplosiveBattery/master
Update 0110.平衡二叉树.md python code via iterate
This commit is contained in:
@ -437,6 +437,31 @@ class Solution:
|
|||||||
return True
|
return True
|
||||||
```
|
```
|
||||||
|
|
||||||
|
层次遍历
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
|
||||||
|
if not root:
|
||||||
|
return True
|
||||||
|
|
||||||
|
que = [root]
|
||||||
|
while que:
|
||||||
|
this_level_length = len(que)
|
||||||
|
for i in range(this_level_length // 2):
|
||||||
|
# 要么其中一个是None但另外一个不是
|
||||||
|
if (not que[i] and que[this_level_length - 1 - i]) or (que[i] and not que[this_level_length - 1 - i]):
|
||||||
|
return False
|
||||||
|
# 要么两个都不是None
|
||||||
|
if que[i] and que[i].val != que[this_level_length - 1 - i].val:
|
||||||
|
return False
|
||||||
|
for i in range(this_level_length):
|
||||||
|
if not que[i]: continue
|
||||||
|
que.append(que[i].left)
|
||||||
|
que.append(que[i].right)
|
||||||
|
que = que[this_level_length:]
|
||||||
|
return True
|
||||||
|
```
|
||||||
|
|
||||||
## Go
|
## Go
|
||||||
|
|
||||||
```go
|
```go
|
||||||
|
@ -531,40 +531,26 @@ class Solution:
|
|||||||
迭代法:
|
迭代法:
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def isBalanced(self, root: TreeNode) -> bool:
|
def isBalanced(self, root: Optional[TreeNode]) -> bool:
|
||||||
st = []
|
|
||||||
if not root:
|
if not root:
|
||||||
return True
|
return True
|
||||||
st.append(root)
|
|
||||||
while st:
|
height_map = {}
|
||||||
node = st.pop() #中
|
stack = [root]
|
||||||
if abs(self.getDepth(node.left) - self.getDepth(node.right)) > 1:
|
while stack:
|
||||||
return False
|
node = stack.pop()
|
||||||
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:
|
if node:
|
||||||
st.append(node) #中
|
stack.append(node)
|
||||||
st.append(None)
|
stack.append(None)
|
||||||
depth += 1
|
if node.left: stack.append(node.left)
|
||||||
if node.right: st.append(node.right) #右
|
if node.right: stack.append(node.right)
|
||||||
if node.left: st.append(node.left) #左
|
|
||||||
else:
|
else:
|
||||||
node = st.pop()
|
real_node = stack.pop()
|
||||||
depth -= 1
|
left, right = height_map.get(real_node.left, 0), height_map.get(real_node.right, 0)
|
||||||
result = max(result, depth)
|
if abs(left - right) > 1:
|
||||||
return result
|
return False
|
||||||
|
height_map[real_node] = 1 + max(left, right)
|
||||||
|
return True
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user