It is common place to use stack to simulate recursion.
Code:
public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> s = new Stack<TreeNode>();
while(root != null || !s.empty()){
while(root!=null){
s.push(root);
root=root.left;
}
if(!s.empty()){
root = s.pop();
result.add(root.val);
root = root.right;
}
}
return result;
}
}
No comments:
Post a Comment