Binary Tree Inorder Traversal

Given a binary tree, return the inorder 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {

ArrayList<Integer> arrayList = new ArrayList<Integer>();

if (root != null) {
arrayList.addAll(inorderTraversal(root.left));
arrayList.add(root.val);
arrayList.addAll(inorderTraversal(root.right));
}

return arrayList;
}
}

非递归:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {

ArrayList<Integer> arrayList = new ArrayList<Integer>();

Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;

while (!stack.empty() || p != null) {

if (p != null) {
stack.push(p);
p = p.left;
} else {
TreeNode pn = stack.pop();
arrayList.add(pn.val);
p = pn.right;
}
}

return arrayList;
}
}