Created
December 27, 2013 07:01
-
-
Save wayetan/8143597 to your computer and use it in GitHub Desktop.
Binary Tree Preorder 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
| /** | |
| * Given a binary tree, return the preorder traversal of its nodes' values. | |
| For example: | |
| Given binary tree {1,#,2,3}, | |
| 1 | |
| \ | |
| 2 | |
| / | |
| 3 | |
| return [1,2,3]. | |
| 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> preorderTraversal(TreeNode root) { | |
| ArrayList<Integer> res = new ArrayList<Integer>(); | |
| if(root == null) | |
| return res; | |
| Stack<TreeNode> s = new Stack<TreeNode>(); | |
| s.push(root); | |
| while(!s.isEmpty()){ | |
| TreeNode tmp = s.pop(); | |
| res.add(tmp.val); | |
| // pay more attention to this sequence. | |
| if(tmp.right != null) | |
| s.push(tmp.right); | |
| if(tmp.left != null) | |
| s.push(tmp.left); | |
| } | |
| return res; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment