Skip to content

Instantly share code, notes, and snippets.

@shharma-vipin
Created August 9, 2019 15:00
Show Gist options
  • Save shharma-vipin/2b8d151d114ab3db4d794007c567444b to your computer and use it in GitHub Desktop.
Save shharma-vipin/2b8d151d114ab3db4d794007c567444b to your computer and use it in GitHub Desktop.
Preorder Traversal without Recursion
public ArrayList<Integer> preorderTraversal(TreeNode A) {
if(A == null) return null;
Stack<TreeNode> stack = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
stack.push(A);
while(!stack.isEmpty()){
TreeNode temp = stack.pop();
result.add(temp.val);
if(temp.right != null){
stack.push(temp.right);
}
if(temp.left != null){
stack.push(temp.left);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment