Inorder Traversal

You have been given a Binary Tree of 'N' nodes, where the nodes have integer values. Your task is to find the In-Order traversal of the given binary tree.

For example :
For the given binary tree:

The Inorder traversal will be [5, 3, 2, 1, 7, 4, 6].
Input Format :
The first line contains an integer 'T' which denotes the number of test cases.

The first line of each test case contains elements of the tree in the level order form. The line consists of values of nodes separated by a single space. In case a node is null, we take -1 in its place.
Example :
The input for the tree is depicted in the below image:

1 3 8 5 2 7 -1 -1 -1 -1 -1 -1 -1

Explanation :

Level 1 :
The root node of the tree is 1

Level 2 :
Left child of 1 = 3
Right child of 1 = 8

Level 3 :
Left child of 3 = 5
Right child of 3 = 2
Left child of 8 =7
Right child of 8 =  null (-1)

Level 4 :
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 2 = null (-1)
Right child of 2 = null (-1)
Left child of 7 = null (-1)
Right child of 7 = null (-1)

1
3 8
5 2 7 -1
-1 -1 -1 -1 -1 -1
Note :
1. The first not-null node(of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.

2. The input ends when all nodes at the last level are null(-1).

3. The above format was just to provide clarity on how the input is formed for a given tree. The sequence will be put together in a single line separated by a single space. Hence, for the above-depicted tree, the input will be given as:

1 3 8 5 2 7 -1 -1 -1 -1 -1 -1 -1
Output Format :
For each test case, return a vector containing the In-Order traversal of a given binary tree.

The first and only line of output of each test case prints 'N' single space-separated integers denoting the node's values in In-Order traversal.
Note :
You don't need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
0 <= N <= 3000
0 <= data <= 10^9     

Where 'data' denotes the node value of the binary tree nodes.

Time limit: 1 sec
AnswerBot
1y

The task is to find the in-order traversal of a given binary tree.

  • Implement a recursive function to perform in-order traversal of the binary tree

  • Start from the left subtree, then visit the root, and f...read more

CodingNinjas
author
2y

This was simple question , here only had to traverse in inorder in a tree

CodingNinjas
author
2y
Recursive Approach

As we can see, before processing any node, the left subtree is processed first, followed by the node, and the right subtree is processed at last. These operations can be defined recursively for each node. The recursive implementation is referred to as a Depth-first search (DFS), as the search tree is deepened as much as possible on each child before going to the next sibling.

 

The steps are as follows :

  1. We create a recursive function inOrderHelper() which takes the root of the tree as an argument.
  2. inOrderHelper() :
    • Visit the left subtree of ‘node’ i.e., call inOrderHelper(‘node’ -> left).
    • Visit ‘node’ and if ‘node’ != NULL then add data of node to answer.
    • Visit the right subtree of ‘node’ i.e., call inOrderHelper(‘node’ -> right).
Space Complexity: O(n)Explanation:

O( N ), where ‘N’ is the total number of nodes in the given binary tree.

 

The space required is proportional to the tree’s height, which can be equal to the total number of nodes in the tree in the worst case for skewed trees.

Hence the space complexity is O( N ).

Time Complexity: O(n)Explanation:

O( N ), where ‘N’ is the total number of nodes in the given binary tree.

 

The recurrence relation is : T( N ) = 2 * T( N / 2 ) + O( 1 ). Apply Master theorem case : c < logba ⁡ where a = 2 , b = 2 , c = 0. For master theorem -----Master_theorem.

Or in simple words, we visit each node of the tree exactly once.

Hence the time complexity is O( N ).


Java (SE 1.8)
/*

Time Complexity: O( N )
Space Complexity: O( N )

where N is the total number of nodes in the given binary tree.
*/

import java.util.*;
import java.io.*;

public class Solution {

public static List < Integer > getInOrderTraversal(TreeNode root) {

// Create answer array to store traversal.
List < Integer > answer = new ArrayList < Integer > ();

// Call inOrderHelper function and store preOrder traversal in answer array.
inOrderHelper(root, answer);

// Return answer.
return answer;
}

// Helper function.
public static void inOrderHelper(TreeNode node, List < Integer > answer) {
// Base case.
if (node == null) {
return;
}

// Visit left subtree.
inOrderHelper(node.left, answer);

// Add data of node to answer.
answer.add(node.data);

// Visit right subtree.
inOrderHelper(node.right, answer);
}
}

Python (3.5)
'''

Time Complexity : O(N)
Space Complexity : O(N)

Where 'N' is the total number of nodes in the binary tree.
'''


def inOrderHelper(root, answer):
# Base case.
if root == None:
return

# Visit left subtree.
inOrderHelper(root.left, answer)

# Add data of node to answer.
answer.append(root.data)

# Visit right subtree.
inOrderHelper(root.right, answer)


def getInOrderTraversal(root):
# Use answer to store traversal of nodes.
answer = []

# Call inOrderHelper function and store inOrder traversal in answer array.
inOrderHelper(root, answer)

# Return answer.
return answer

C++ (g++ 5.4)
/*

Time Complexity: O( N )
Space Complexity: O( N )

where ‘N’ is the total number of nodes in the given binary tree.
*/

void inOrderHelper(TreeNode *node, vector &answer)
{
// Base case.
if (node == NULL)
{
return;
}

// Visit left subtree.
inOrderHelper(node->left, answer);

// Add data of node to answer.
answer.push_back(node->data);

// Visit right subtree.
inOrderHelper(node->right, answer);
}

vector getInOrderTraversal(TreeNode *root)
{
// Use answer to store traversal of nodes.
vector answer;

// Call inOrderHelper function and store inOrder traversal in answer array.
inOrderHelper(root, answer);

// Return answer.
return answer;
}
CodingNinjas
author
2y
Iterative Approach

To convert the above recursive procedure into an iterative one, we need an explicit stack.

The steps are as follows :

  1. Create an empty stack and initialize the current node as root.
  2. Run...read more
CodingNinjas
author
2y
Morris Traversal

The idea here is to use Morris traversal for the Inorder traversal of the tree. The idea of Morris's traversal is based on the Threaded Binary Tree.  In this traversal, we will create links to the predecessor back to the current node so that we can trace it back to the top of a binary tree. Here we don’t need to find a predecessor for every node, we will be finding a predecessor of nodes with only a valid left child.

 

So Finding a predecessor will take O( N ) as time as we will be visiting every edge at most two times and there are only ‘N’ - 1 edges in a binary tree. Here ‘N’ is the total number of nodes in a binary tree.

 

For more details, please check the Threaded binary tree and Explanation of Morris Method

 

The steps are as follows :

  1. Create a new node, say ‘CURRENT’, and initialize it as ‘ROOT’.
  2. Run a loop until ‘CURRENT’ !=NULL and do:
    • If CURRENT -> left = NULL then add data of current to answer and do CURRENT = CURRENT -> right
    • Else In current’s left subtree, make ‘CURRENT’ as of the right child of rightmost node and visit this left child i.e. CURRENT = CURRENT -> left.
Space Complexity: O(1)Explanation:

O( 1 )

 

In the worst-case constant space is required.

Hence the space complexity is O( 1 ).

Time Complexity: O(n)Explanation:

O( N ), where ‘N’ is the total number of nodes in the given binary tree.

 

In the worst case, we are visiting each node at most twice in Inorder traversal.

Hence the time complexity is O( N ).


Java (SE 1.8)
/*

Time Complexity: O( N )
Space Complexity: O( 1 )

where N is the total number of nodes in the given binary tree.
*/

import java.util.*;
import java.io.*;

public class Solution {

public static List < Integer > getInOrderTraversal(TreeNode root) {

// Create answer array to store traversal.
List < Integer > answer = new ArrayList < Integer > ();

// Base case.
if (root == null) {
return answer;
}

// 'PREDECESSOR' and 'CURRENT' will store predecessor and current nodes, respectively.
TreeNode current, predecessor;

// Initialize current node as 'ROOT'.
current = root;

// Run a loop until 'CURRENT' != NULL.
while (current != null) {

if (current.left == null) {

// Add current node data to answer.
answer.add(current.data);

// Move to right child of current.
current = current.right;
} else {

// Find predecessor of current node.
predecessor = current.left;
while (predecessor.right != null && predecessor.right != current) {
predecessor = predecessor.right;
}

if (predecessor.right == null) {
/*
Make a link between predecessor and current node
so that we have a path to come back to current
when we have traversed the whole left subtree.
*/
predecessor.right = current;
current = current.left;
} else {
/*
If right node of predecessor is not NULL then it
means we have traversed the whole left subtree.
So we unlink the connection between current and predecessor
and move to right node of current.
*/
predecessor.right = null;
answer.add(current.data);
current = current.right;
}
}
}

// Return answer.
return answer;
}
}

C++ (g++ 5.4)
/*

Time Complexity: O( N )
Space Complexity: O( 1 )

where ‘N’ is the total number of nodes in the given binary tree.
*/

// Morris Traversal for inOrder.
vector getInOrderTraversal(TreeNode *root)
{

// Create answer array to store traversal.
vector answer;

// Base case.
if (root == NULL)
{
return answer;
}

// 'PREDECESSOR' and 'CURRENT' will store predecessor and current nodes, respectively.
TreeNode *current, *predecessor;

// Initialize current node as 'ROOT'.
current = root;

// Run a loop until 'CURRENT' != NULL.
while (current != NULL)
{
if (current->left == NULL)
{
answer.push_back(current->data);
current = current->right;
}
else
{

// Find the rightmost node on the left subtree of current.
predecessor = current->left;
while (predecessor->right != NULL && predecessor->right != current)
{
predecessor = predecessor->right;
}

if (predecessor->right == NULL)
{
/*
Make a link between predecessor and current node
So that we have a path to come back to current
When we have traversed the whole left subtree.
*/
predecessor->right = current;
current = current->left;
}
else
{
/*
If right node of predecessor is not NULL then it
Means we have traversed the whole left subtree.
So we unlink the connection between current and predecessor
And move to right node of current.
*/
predecessor->right = NULL;
answer.push_back(current->data);
current = current->right;
}
}
}

return answer;
}

Python (3.5)
'''

Time Complexity : O(N)
Space Complexity : O(1)

Where 'N' is the total number of nodes in the binary tree.
'''


def getInOrderTraversal(root):
# Use answer to store traversal of nodes.
answer = []

# Base case.
if (root == None):
return answer

# 'PREDECESSOR' and 'CURRENT' will store predecessor and current nodes, respectively.
current = None
predecessor = None

# Initialize current node as 'ROOT'.
current = root

# Run a loop until 'CURRENT' != None.
while (current != None):
if (current.left == None):
answer.append(current.data)
current = current.right
else:
# Find the rightmost node on the left subtree of current.
predecessor = current.left
while (predecessor.right != None and predecessor.right != current):
predecessor = predecessor.right

if (predecessor.right == None):
'''
Make a link between predecessor and current node
So that we have a path to come back to current
When we have traversed the whole left subtree.
'''
predecessor.right = current
current = current.left
else:
'''
If right node of predecessor is not None then it
Means we have traversed the whole left subtree.
So we unlink the connection between current and predecessor
And move to right node of current.
'''
predecessor.right = None
answer.append(current.data)
current = current.right

# Return answer.
return answer
Add answer anonymously...
Jio Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter