Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created August 22, 2017 22:35
Show Gist options
  • Select an option

  • Save cixuuz/43c39efc9a0359076bda51319758c09d to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/43c39efc9a0359076bda51319758c09d to your computer and use it in GitHub Desktop.
[144. Binary Tree Preorder Traversal] #leetcode
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode curNode = root;
while ( !stack.isEmpty() || curNode != null) {
if (curNode != null) {
result.add(curNode.val);
stack.push(curNode);
curNode = curNode.left;
} else {
curNode = stack.pop().right;
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment