Created
February 8, 2014 22:52
-
-
Save Jeffwan/8891544 to your computer and use it in GitHub Desktop.
Binary Tree Preorder Traversal @leetcode
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
| package leetcode.tree; | |
| import java.util.ArrayList; | |
| import java.util.Stack; | |
| import leetcode.tree.InorderTraversal.TreeNode; | |
| public class PreorderTraversal { | |
| public ArrayList<Integer> preorderTraversal(TreeNode root) { | |
| TreeNode node = root; | |
| Stack<TreeNode> stack = new Stack<TreeNode>(); | |
| ArrayList<Integer> arrayList = new ArrayList<Integer>(); | |
| while (node != null || stack.size() > 0) { | |
| while (node != null) { | |
| arrayList.add(node.val); | |
| stack.push(node); | |
| node = node.left; | |
| } | |
| if (stack.size() > 0) { | |
| node = stack.pop(); | |
| node = node.right; | |
| } | |
| } | |
| return arrayList; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment