Created
February 3, 2020 04:51
-
-
Save andriybuday/2bb3448ec3021aeb0ee439db1ae9d1c1 to your computer and use it in GitHub Desktop.
InOrder Binary Tree Traversal
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
// recursive | |
public List<Integer> inorderTraversal(TreeNode root) { | |
List<Integer> ans = new ArrayList(); | |
if(root == null) return ans; | |
ans.addAll(inorderTraversal(root.left)); | |
ans.add(root.val); | |
ans.addAll(inorderTraversal(root.right)); | |
return ans; | |
} | |
// iterative | |
public List<Integer> inorderTraversal(TreeNode root) { | |
List<Integer> ans = new ArrayList(); | |
Deque<TreeNode> stack = new LinkedList(); | |
while(root != null || !stack.isEmpty()) { | |
while(root != null) { | |
stack.push(root); | |
root = root.left; | |
} | |
root = stack.pop(); | |
ans.add(root.val); | |
root = root.right; | |
} | |
return ans; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment