Binary Tree Inorder Traversal
Problem Statement
Published in
2 min readJan 20, 2016
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3}
,
1
\
2
/
3
return [1,3,2]
.
Approach
There are 2 ways I know of solving this problem:
- Maintain of stack of the left most nodes.
- Pop the top element from the stack-> add the value of this node to the list -> push the right subtree of this node into the stack.
- Perform the above step until the stack is empty. The elements added to the list will be the result of inorder traversal.
Another approach is simple:
- Starting from the root node, keep adding to the list in the following order
- If left node is not null then recursively call addToList(node.left)
- Add value of the current node to the list.
- If right node is not null then recursively call addToList(node.right)
In this approach there is no need of maintaining a stack.
Run Time Complexity
The run time for the first approach is O(n logn). Cost of pushToLeft() is O(lgn) and this called for n elements so the totals becomes O(nlogn)
The run time for the second approach is clearly O(n)
Code for Approach1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> result = new ArrayList<Integer>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null){
return result;
}
pushToLeft(root);
while(!stack.empty()){
TreeNode node = stack.pop();
result.add(node.val);
pushToLeft(node.right);
}
return result;
}
private void pushToLeft(TreeNode node){
if(node != null){
stack.push(node);
pushToLeft(node.left);
}return;
}}
Code for Approach2
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<Integer> result = new ArrayList<Integer>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null){
return result;
}
addToList(root);
return result;
}
private void addToList(TreeNode node){
if(node.left != null){
addToList(node.left);
}
result.add(node.val);
if(node.right != null){
addToList(node.right);
}
}
}