Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created September 2, 2013 19:05
Show Gist options
  • Save charlespunk/6416221 to your computer and use it in GitHub Desktop.
Save charlespunk/6416221 to your computer and use it in GitHub Desktop.
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
/**
* Definition for binary tree
* 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> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode run = root;
while(run != null){
stack.add(run);
run = run.left;
}
while(!stack.isEmpty()){
run = stack.pop();
result.add(run.val);
run = run.right;
while(run != null){
stack.add(run);
run = run.left;
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment