-
-
Save InterviewBytes/3eeedfb3252096be3b0b8ad77070e8ef to your computer and use it in GitHub Desktop.
Preorder iterative
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
package com.interviewbytes.trees; | |
import java.util.ArrayDeque; | |
import java.util.ArrayList; | |
import java.util.Deque; | |
import java.util.List; | |
public class PreorderIterative { | |
public List<Integer> preorderTraversal(TreeNode root) { | |
List<Integer> list = new ArrayList<>(); | |
Deque<TreeNode> stack = new ArrayDeque<>(); | |
if (root != null) stack.push(root); | |
while (!stack.isEmpty()) { | |
TreeNode node = stack.pop(); | |
if (node.right != null) stack.push(node.right); | |
if (node.left != null) stack.push(node.left); | |
list.add(node.val); | |
} | |
return list; | |
} | |
} |
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
package com.interviewbytes.trees; | |
public class TreeNode { | |
int val; | |
TreeNode left; | |
TreeNode right; | |
TreeNode(int x) { | |
val = x; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment