1. 题目描述
给定一个二叉树,返回它的 前序 遍历。 示例: 输入: [1,null,2,3] 1 2 / 3 输出: [1,2,3]
2. 代码实现
递归方式:
class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ l = [] self.visitNode(root, l) return l def visitNode(self, root, l): if root is None: return l.append(root.val) self.visitNode(root.left, l) self.visitNode(root.right, l)
非递归方式:
class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ stack = [] stack.append(root) res = [] while stack: node = stack.pop() if node is None: continue res.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return res