一、思路
- 递归遍历代码非常统一,只需要改变顺序即可,而迭代遍历中序的代码修改较多,现提出较为统一的迭代法
- 做标记:不论是否处理过,均进行入栈,但处理过的元素入栈后,再入栈一个
null
值作为标记,当遍历到null
值时,继续pop
出其前方处理过的元素,加入结果列表
文字描述有点难理解,可以做一个1~7的二叉树手动试试
二、代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
result = []
st= []
if root:
st.append(root)
while st:
node = st.pop()
if node != None:
if node.right: #右
st.append(node.right)
if node.left: #左
st.append(node.left)
st.append(node) #中
st.append(None)
else:
node = st.pop()
result.append(node.val)
return result
中序和后序只需要改变【右,左,中】的顺序即可,分别改为【右,中,左】,【中,右,左】
三、总结
- 这一方法个人感觉还是很好用的,比递归法好理解,比普通的迭代法更统一。
部分内容参考代码随想录