Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created January 6, 2015 03:51
Show Gist options
  • Save kanrourou/b70fdfd3414005d8251c to your computer and use it in GitHub Desktop.
Save kanrourou/b70fdfd3414005d8251c to your computer and use it in GitHub Desktop.
/**
* 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