Binary Tree Preorder Traversal

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

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

描述

给定一个二叉树,返回前序遍历的值,采用非递归方式

分析

非递归方式主要使用 Stack 来模拟递归

代码

递归:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 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> list = new ArrayList<Integer>();

if (root != null) {

list.add(root.val);
list.addAll(preorderTraversal(root.left));
list.addAll(preorderTraversal(root.right));
}

return list;
}
}

非递归:

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
27
28
29
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {

List<Integer> list = new ArrayList<Integer>();

if (root == null) {
return list;
}

Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);

while (!stack.empty()) {

TreeNode treeNode = stack.pop();
list.add(treeNode.val);

if (treeNode.right != null) {
stack.push(treeNode.right);
}

if (treeNode.left != null) {
stack.push(treeNode.left);
}
}

return list;
}
}