Created
September 2, 2013 19:05
-
-
Save charlespunk/6416221 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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? |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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