forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution2.java
48 lines (40 loc) · 1.37 KB
/
Solution2.java
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/// Source : https://leetcode.com/problems/binary-tree-inorder-traversal/
/// Author : liuyubobobo
/// Time : 2017-11-17
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
// My Non-Recursive
// Time Complexity: O(n), n is the node number in the tree
// Space Complexity: O(h), h is the height of the tree
public class Solution2 {
private class Command{
String s; // go, print
TreeNode node;
Command(String s, TreeNode node){
this.s = s;
this.node = node;
}
};
public List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(root == null)
return res;
Stack<Command> stack = new Stack<Command>();
stack.push(new Command("go", root));
while(!stack.empty()){
Command command = stack.pop();
if(command.s.equals("print"))
res.add(command.node.val);
else{
assert command.s.equals("go");
if(command.node.right != null)
stack.push(new Command("go",command.node.right));
stack.push(new Command("print", command.node));
if(command.node.left != null)
stack.push(new Command("go",command.node.left));
}
}
return res;
}
}