Skip to content

Instantly share code, notes, and snippets.

@andriybuday
Created February 3, 2020 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andriybuday/2bb3448ec3021aeb0ee439db1ae9d1c1 to your computer and use it in GitHub Desktop.
Save andriybuday/2bb3448ec3021aeb0ee439db1ae9d1c1 to your computer and use it in GitHub Desktop.
InOrder Binary Tree Traversal
// 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