导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-144.Binary Tree Preorder Traversal

题目

Given a binary tree, return the preorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3} ,
 1
  \
   2
  /
 3
return  [1,2,3] .

Note: Recursive solution is trivial, could you do it iteratively?

翻译

给出一颗二叉树,返回先序遍历序列。
例如:给出二叉树 {1, #, 2, 3}。
 1
  \
   2
  /
 3
返回 [1,2,3]。
注意:递归解法很普通,你能否用非递归方法解出?

解:
递归:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {


public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
preorderTraversal(root, res);
return res;
}

public void preorderTraversal(TreeNode root, List<Integer> res) {
if (root == null)
return;
res.add(root.val);
preorderTraversal(root.left, res);
preorderTraversal(root.right, res);
}
}

非递归:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {

public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) return res;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
stack.push(node);
while (!stack.isEmpty()) {
node = stack.pop();
res.add(node.val);
if (node.right != null) stack.push(node.right);
if (node.left != null) stack.push(node.left);
}
return res;
}
}