-
-
Save InterviewBytes/e33f945d50a8cb56fdf940eb504e5583 to your computer and use it in GitHub Desktop.
Inorder traversal Iterative approach
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 InorderTraversalIterative { | |
public List<Integer> inorderTraversal(TreeNode root) { | |
List<Integer> list = new ArrayList<>(); | |
Deque<TreeNode> stack = new ArrayDeque<>(); | |
TreeNode current = root; | |
while (current != null || !stack.isEmpty()) { | |
if (current != null) { | |
stack.push(current); | |
current = current.left; | |
} else { | |
current = stack.pop(); | |
list.add(current.val); | |
current = current.right; | |
} | |
} | |
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