# 【LeetCode题解】144_二叉树的前序遍历

## 描述

输入: [1,null,2,3]
1
\
2
/
3

## 方法一：递归

### Java 代码

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
preorderTraversal(root, res);
return res;
}

private void preorderTraversal(TreeNode root, List<Integer> res) {
if (root == null) {
return;
}

preorderTraversal(root.left, res);
preorderTraversal(root.right, res);
}
}

• 时间复杂度：$O(n)$，其中，$n$ 为二叉树节点的数目
• 空间复杂度：$O(n)$

### Python 代码

# 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]
"""
def dfs(root, ret):
if root is None:
return

ret.append(root.val)
dfs(root.left, ret)
dfs(root.right, ret)

ret = list()
dfs(root, ret)
return ret

## 方法二：非递归（使用栈）

### Java 代码

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}

Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();

if (cur.right != null) {
stack.push(cur.right);
}
if (cur.left != null) {
stack.push(cur.left);
}
}
return res;
}
}

• 时间复杂度：$O(n)$，其中，$n$ 为二叉树节点的数目
• 空间复杂度：$O(h)$，其中，$h$ 为二叉树的高度

### Python 代码

# 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 root is None:
return []

ret, stack = [], [root]
while len(stack) > 0:
node = stack.pop()
ret.append(node.val)

if node.right is not None:
stack.append(node.right)
if node.left is not None:
stack.append(node.left)

return ret

posted @ 2018-10-11 23:36 StrongXGP 阅读(...) 评论(...) 编辑 收藏