/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> Stack = new Stack<TreeNode>();
TreeNode current = root;
boolean done = false;
while(!done){
if(current != null){
Stack.push(current);
current = current.left;
}
else{
if(Stack.isEmpty()){
done = true;
}
else{
current = Stack.pop();
list.add(current.val);
current = current.right;
}
}
}
return list;
}
}
===========================================================================
Easily read this one
Java: BSTInOrder
01 public ArrayList<Integer> inorderTraversal(TreeNode root) {
02 ArrayList<Integer> result=new ArrayList<Integer>();
03 Stack<TreeNode> st=new Stack<TreeNode>();
04 if(root!=null)
05 {
06 st.push(root);
07 while(root.left!=null)
08 {
09 root=root.left;
10 st.push(root);
11 }
12 }
13 while(!st.empty())
14 {
15 TreeNode top=st.pop();
16 result.add(top.val);
17 if(top.right!=null)
18 {
19 st.push(top.right);
20 top=top.right;
21 while(top.left!=null)
22 {
23 top=top.left;
24 st.push(top);
25 }
26 }
27 }
28
29 return result;
30 }