Update 0110.平衡二叉树.md python code via iterate

In the original method, we need to traversal every node and write the function named getDepth to get the depth of all sub trees in traverse method too.
But there is more suitable uniform iteration traversal algorithm, I use the map struct in the code segment where the node is Null.
If you have problem in understand, please feel free to communicate with me.
This commit is contained in:
ExplosiveBattery
2022-06-09 00:58:38 +08:00
committed by GitHub
parent 87abfa1664
commit cded6c5c80

View File

@ -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
``` ```