Created
August 9, 2019 15:00
-
-
Save shharma-vipin/2b8d151d114ab3db4d794007c567444b to your computer and use it in GitHub Desktop.
Preorder Traversal without Recursion
This file contains 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
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