Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created January 5, 2015 22:18
Show Gist options
  • Save kanrourou/f1d21d39070dbbe22601 to your computer and use it in GitHub Desktop.
Save kanrourou/f1d21d39070dbbe22601 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;
Stack<TreeNode> path = new Stack<TreeNode>();
while(!path.isEmpty() || curr != null) {
while (curr != null) {
path.push(curr);
res.add(curr.val);
curr = curr.left;
}
curr = path.pop();
curr = curr.right;
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment