144. 中序遍历的迭代解法
https://leetcode.com/problems/binary-tree-preorder-traversal/
思路
递归方法
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
res = []
self.preorder(root, res)
return res
def preorder(self, root, res):
res.append(root.val)
if root.left:
self.preorder(root.left, res)
if root.right:
self.preorder(root.right, res)
可以使用栈, 先进后出, 每次出节点, 把其右子节点, 左节点入栈. 右边的节点在栈底层, 左边的节点在栈高层.
迭代方法(使用栈)
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
res = []
stack = [root]
while stack:
node = stack.pop()
res.append(node.val)
# 后加入的左节点将先出栈
if node.right: stack.append(node.right)
if node.left: stack.append(node.left)
return res
145. Binary Tree Postorder Traversal 后序遍历的迭代解法
因为后序遍历的顺序是 左->右->中, 其逆序遍历是 中->左->右(更容易求出), 类似于前序遍历, 我们得到逆后序遍历序列后只要反转即可得到后序遍历序列.
"""
只需要将上一题中右节点先入栈改成左节点先入栈即可.
"""
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
res = []
stack = [root]
while stack:
node = stack.pop()
res.append(node.val)
# 后加入的左节点将先出栈
if node.left: stack.append(node.left)
if node.right: stack.append(node.right)
return res[::-1]
补充: 前序遍历的迭代解法