Created
January 6, 2015 03:51
-
-
Save kanrourou/b70fdfd3414005d8251c 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
/** | |
* 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) { | |
List<Integer> res = new ArrayList<Integer>(); | |
if (root == null) | |
return res; | |
TreeNode curr = root; | |
while (curr != null) { | |
if (curr.left == null) { | |
res.add(curr.val); | |
curr = curr.right; | |
} else { | |
TreeNode temp = curr.left; | |
while (temp.right != null && temp.right != curr) { | |
temp = temp.right; | |
} | |
if (temp.right == null) { | |
temp.right = curr; | |
res.add(curr.val); | |
curr = curr.left; | |
} else { | |
temp.right = null; | |
curr = curr.right; | |
} | |
} | |
} | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment