94.二叉树的中序遍历 python3
程序员文章站
2024-01-11 16:42:34
...
题目:
思路:
- 深度优先
代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
result = []
visited = set([])
sta = deque([])
if root:
sta.append(root)
while sta:
front = sta.pop()
if front not in visited:
visited.add(front)
if front.right:
sta.append(front.right)
sta.append(front)
if front.left:
sta.append(front.left)
else:
result.append(front.val)
return result
总结:
- 迭代实现的深度优先算法,打败93%的人,出乎意料。
下一篇: MySQL延迟从库