144. 二叉树的前序遍历
迭代
- 先找到最左边的点
- 一步一步退回来加上右边的点
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res = []
if not root:
return res
stack = []
node = root
while stack or node:
while node:
res.append(node.val)
stack.append(node)
node = node.left
node = stack.pop()
node = node.right
return res
递归
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
def preorder(root: TreeNode):
if not root:
return
res.append(root.val)
preorder(root.left)
preorder(root.right)
res = []
preorder(root)
return res
94. 二叉树的中序遍历
迭代
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
if not root:
return res
stack = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
res.append(node.val)
node = node.right
return res
递归
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
def preorder(root: TreeNode):
if not root:
return
preorder(root.left)
res.append(root.val)
preorder(root.right)
res = []
preorder(root)
return res
145. 二叉树的后序遍历
迭代
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
res = []
if not root:
return res
stack = []
node = root
prev = None
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
if not node.right or node.right == prev:
res.append(node.val)
prev = node
node = None
else:
stack.append(node)
node = node.right
return res
递归
def preorder(root: TreeNode):
if not root:
return
res.append(root.val)
preorder(root.left)
preorder(root.right)
res = []
preorder(root)
return res