首先简单介绍一下这三种遍历算法的主要思想:
前序遍历:根节点——左子树——右子树
中序遍历:左子树——根节点——右子树
后序遍历:左子树——右子树——根节点
接下来分递归和非递归两种方式来介绍这三种遍历算法,对于前序遍历有:
递归算法:
class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: ans = [] self.iteration(root, ans) return ans def iteration(self, root: TreeNode, ans: List[int]) -> None: if root: ans.append(root.val) self.iteration(root.left, ans) self.iteration(root.right, ans)
非递归算法:
class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] current, stack, ans = root, [], [] while current or stack: while current: # 遍历当前节点 ans.append(current.val) # 添加根节点的值 stack.append(current) current = current.left # 访问左子树