Created
February 28, 2015 22:57
-
-
Save dmnugent80/e19dcd03e0ac58a789d8 to your computer and use it in GitHub Desktop.
Iterative Binary Tree Pre-order Traversal
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 List<Integer> preorderTraversal(TreeNode root) { | |
TreeNode node = root; | |
Stack<TreeNode> stack = new Stack<TreeNode>(); | |
List<Integer> retList = new ArrayList<Integer>(); | |
while (true){ | |
if (node != null){ | |
retList.add(node.val); | |
stack.push(node); | |
node = node.left; | |
}else{ | |
if (stack.empty()){ | |
return retList; | |
} | |
node = stack.pop(); | |
node = node.right; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment