一、二叉树的前序遍历(LeetCode 144)
递归实现:
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] return [root.val] +self.preorderTraversal(root.left)+self.preorderTraversal(root.right)
非递归实现:
class Solution: def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res=[] stack=[root] while stack: node=stack.pop() if node: res.append(node.val) stack.append(node.right) stack.append(node.left) return res
二、二叉树的中序遍历(LeetCode 94)
递归实现:
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] return self.inorderTraversal(root.left)+[root.val]+self.inorderTraversal(root.right)
非递归实现:
class Solution: def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res,stack=[],[] while True: while root: stack.append(root) root=root.left if not stack: return res node=stack.pop() res.append(node.val) root=node.right return res
三、二叉树的后序遍历(LeetCode 145)
递归实现:
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] return self.postorderTraversal(root.left)+self.postorderTraversal(root.right)+[root.val]
非递归实现:
class Solution: def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res=[] stack=[root] while stack: node=stack.pop() if node: res.append(node.val) stack.append(node.left) stack.append(node.right) return res[::-1]