Boundary Traversal of Binary Tree

Hard
0/120
Average time to solve is 20m
profile
Contributed by
460 upvotes
Asked in companies
Morgan StanleyMicrosoftSalesforce

Problem statement

You are given a binary tree having 'n' nodes.


The boundary nodes of a binary tree include the nodes from the left and right boundaries and the leaf nodes, each node considered once.


Figure out the boundary nodes of this binary tree in an Anti-Clockwise direction starting from the root node.


Example :
Input: Consider the binary tree A as shown in the figure:

alt text

Output: [10, 5, 3, 7, 18, 25, 20]

Explanation: As shown in the figure

The nodes on the left boundary are [10, 5, 3]

The nodes on the right boundary are [10, 20, 25]

The leaf nodes are [3, 7, 18, 25].

Please note that nodes 3 and 25 appear in two places but are considered once.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The only line contains elements 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.

For example, the input for the tree depicted in the below image will be:

alt text

1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1

Explanation :
Level 1 :
The root node of the tree is 1

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

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

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

Level 5 :
Left child of 7 = null (-1)
Right child of 7 = null (-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.

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

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 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1


Output Format:
Print the boundary nodes of the given binary tree separated by single spaces.


Note :
You do not need to print anything; it has already been taken care of. Just implement the given function.
Sample Input 1:
10 5 20 3 8 18 25 -1 -1 7 -1 -1 -1 -1 -1 -1 -1
Sample Output 1:
10 5 3 7 18 25 20
Explanation of Sample Input 1:
The nodes on the left boundary are [10, 5, 3]

The nodes on the right boundary are [10, 20, 25]

The leaf nodes are [3, 7, 18, 25].

Please note that nodes 3 and 25 appear in two places but are considered once.
Sample Input 2:
100 50 150 25 75 140 200 -1 30 70 80 -1 -1 -1 -1 -1 35 -1 -1 -1 -1 -1 -1
Sample Output 2:
100 50 25 30 35 70 80 140 200 150
Constraints:
1 <= n <= 10000

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

Time Limit: 1 sec
Hint

Traverse those three boundaries separately and then combine the result.

Approaches (1)
Recursion Based Approach

The boundary traversal of a binary tree can be broken down into 4 parts. These parts are given in the same order as they are present in the traversal-

 

  1. The root node - The root node will always be our first node in the whole boundary traversal.
     
  2. The left boundary - The left most nodes of the left subtree are also included in the boundary traversal, so we will process them next except for the leaf node as it will be processed in our next part. We can use recursion for this and traverse for only left child until a leaf node is encountered. If the left child is not present we recurse for the right child.
     
  3. The leaf Nodes - The leaf nodes of the binary tree will be processed next. We can use a simple inorder traversal for that. Inorder traversal will make sure that we process leaf nodes from left to right.
     
  4. The right boundary - The right most nodes of the right subtree will be processed at last in reverse order except for the leaf node as it is already processed in the previous part. For this, we can use recursion in a postorder manner and traverse for the right child only until we encounter a leaf node. If the right child is not present we will recurse for the left child. The postorder recursion will make sure that we traverse the right boundary in reverse order.
Time Complexity

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

Since we are traversing for left and right boundaries in a binary tree, and this will take at the most linear time. Also, traversing for leaf nodes can also be performed in linear time. Hence, the overall time complexity is O(n).

Space Complexity

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

The recursion stack can grow at the maximum height of the binary tree. In the worst-case scenario, the height of a binary tree can be up to n (Skewed Trees). Hence the overall space complexity will be O(n).

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Boundary Traversal of Binary Tree
All tags
Sort by
Search icon

Interview problems

C++ Solution

 

// left traversal

void traverseleft (TreeNode<int>*root, vector<int>&ans){

    if(root==NULL || root->left ==NULL && root->right==NULL){

        return;

    }

    ans.push_back(root->data);

    if(root->left){

        traverseleft(root->left,ans);

    }else{

        traverseleft(root->right,ans);

    }

}

// leaf Node trraversal

void traversalEaf(TreeNode<int>*root, vector<int>&ans){

    if(root==NULL){

        return;        

    }

    if(root->left == NULL && root->right==NULL){

        ans.push_back(root->data);

        return;

    }

    traversalEaf(root->left,ans);

    traversalEaf(root->right,ans);

}

 

// right NOde traversal

void  traverseright(TreeNode<int>*root, vector<int>&ans){

    if(root==NULL || root->left ==NULL && root->right==NULL){

        return;

    }

    if(root->right){

        traverseright(root->right,ans);

        }else{

            traverseright(root->left, ans);

        }

        ans.push_back(root->data);

}

 

vector<int> traverseBoundary(TreeNode<int> *root)

{

    // Write your code here.

    vector<int> ans;

    if (root == NULL) {

            return ans;

    }

        ans.push_back(root->data);

        traverseleft(root->left, ans);

        traversalEaf(root->left, ans);

        traversalEaf(root->right, ans);

        traverseright(root->right, ans);

 

}

 

7 views
0 replies
0 upvotes

Interview problems

best in c++

/************************************************************

    Following is the Binary Tree node structure:

    template <typename T>
    class TreeNode
    {
    public:
        T data;
        TreeNode<T> *left;
        TreeNode<T> *right;

        TreeNode(T data)
        {
            this -> data = data;
            left = NULL;
            right = NULL;
        }

        ~TreeNode()
        {
            if(left)
                delete left;
            if(right)
                delete right;
        }
    };

************************************************************/

void traverseLeft(TreeNode<int>* root , vector<int> &ans){
    if((root==NULL) || (root->left==NULL && root->right==NULL)){
        return;
    }

    ans.push_back(root->data);
    if(root->left){
        traverseLeft(root->left,ans);
    }
    else{
        traverseLeft(root->right,ans);
    }
}

void traverseLeaf(TreeNode<int>* root, vector<int> &ans){
    if(root==NULL){
        return;
    }
    if(root->left==NULL && root->right==NULL){
        ans.push_back(root->data);
    }
    traverseLeaf(root->left,ans);
    traverseLeaf(root->right,ans);
}


void traverseRight(TreeNode<int>* root , vector<int> &ans){
    if((root==NULL) || (root->left==NULL && root->right==NULL)){
        return;
    }
    if(root->right){
        traverseRight(root->right,ans);
    }
    else{
        traverseRight(root->left,ans);
    }
    ans.push_back(root->data);
}


vector<int> traverseBoundary(TreeNode<int> *root)
{
	

    vector<int> ans;
    if(root==NULL){
        return ans;
    }

    ans.push_back(root->data);
    // left ko traverse
    traverseLeft(root->left,ans);
    // leaf node
        // left subtree-> 
        traverseLeaf(root->left,ans);
        // right subtree
        traverseLeaf(root->right,ans);
    // right ko traverse
    traverseRight(root->right,ans);
    return ans;
}
9 views
0 replies
0 upvotes

Interview problems

Wrong test case

In your system you are showing input tree is  10 5 20 3 8 18 25 -1 -1 7 -1 -1 -1 -1 -1 -1 -1 and correct answer is 10 5 3 7 18 25 20  like really you guys out of mid see input have 8 node and you guys are saying 7 output nodes are correct   

40 views
0 replies
0 upvotes

Interview problems

stepwise java code easy explanation

step1: include root node,checking that root node is not leaf node.

step2: move towars left part of tree,if node has left then that will be our answer,and if node does not have left then right node will be our answer.

step3: Do preOrder traversal (or any traversal- pre/In/post)and find leaf node.

step4:move towards right part of tree,if node has right then that will be our answer,and if node does not have right then left node will be our answer.

 

import java.util.*;

 

public class Solution 

{

    public static List<Integer> traverseBoundary(TreeNode root)

    {

        // Write your code here.

        List<Integer> list=new ArrayList<Integer>();

 

        //step 1: include root (if root is not leaf)

        if(! isLeaf(root) )

        {

            list.add(root.data);

        }

        //step 2: include left boundary (movement in left part of root)

        leftBoundary(root,list);

        //step 3: include leaf  (pre order traversal on entire tree)

        leafNode(root,list);

        //step 4: include right boundary(movement in right part of root)

        rightBoundary(root,list);

 

        return list;

    }

    

    public static void leftBoundary(TreeNode node,List list)

    {

        TreeNode leftNode=node.left;

        while(leftNode!=null)

        {

            //step A: is this node is leaf

            if(isLeaf(leftNode))

            {

                break;

            }

 

            // not leaf,include in left boundary

            list.add(leftNode.data);

 

            //updating while condition

            if(leftNode.left!=null) //agar left exist---> include in leftBoundary

            leftNode=leftNode.left;

            else     //agar left not exist,only then right child will be in leftBoundary

            leftNode=leftNode.right;

 

        }

 

 

    }

    public static void rightBoundary(TreeNode node,List list)

    {

        TreeNode rightNode=node.right;

        Stack<Integer> st=new Stack<>();

        while(rightNode!=null)

        {

            //step A: is this node is leaf

            if(isLeaf(rightNode))

            {

                break;

            }

 

            // not leaf,include in right boundary

            // list.add(rightNode.data);

 

            // storing data in stack bcz we need rightboundary data in reverse order

            st.push(rightNode.data);

 

            //updating while condition

            if(rightNode.right!=null) //agar left exist---> include in leftBoundary

            rightNode=rightNode.right;

            else     //agar left not exist,only then right child will be in leftBoundary

            rightNode=rightNode.left;

 

        }

        // storing data in list from stack

        while(! st.isEmpty() ) //while(st.size()>0)

        {

           list.add(st.pop());

        }

 

    }

    public static void leafNode(TreeNode node,List list)

    {

       if(node==null)

       return;

 

       if(isLeaf(node))

       list.add(node.data);

       

       leafNode(node.left,list);

       leafNode(node.right,list);

 

    }

    public static boolean isLeaf(TreeNode node)

    {

        return (node.left==null && node.right==null);

    }

}

 

41 views
0 replies
0 upvotes

Interview problems

Boundary Traversal of Binary Tree || Easy 3 step C++ Sulution

bool isLeaf(TreeNode<int>* node) {
    return node != NULL && node->left == NULL && node->right == NULL;
}

void leftBoundary(TreeNode<int>* root, vector<int>& ans) {
    TreeNode<int>* node = root;
    while (node) {
        if (!isLeaf(node)) {
            ans.push_back(node->data);
        }
        if (node->left) {
            node = node->left;
        } else {
            node = node->right;
        }
    }
}

void rightBoundary(TreeNode<int>* root, vector<int>& ans) {
    TreeNode<int>* node = root;
    vector<int> ds;
    while (node) {
        if (!isLeaf(node)) {
            ds.push_back(node->data);
        }
        if (node->right) {
            node = node->right;
        } else {
            node = node->left;
        }
    }
   
    for (int i = ds.size() - 1; i >= 0; i--) {
        ans.push_back(ds[i]);
    }
}

void leafNodes(TreeNode<int>* node, vector<int>& ans) {
    if (node == NULL) {
        return;
    }
    if (isLeaf(node)) {
        ans.push_back(node->data);
        return;
    }
    if (node->left) {
        leafNodes(node->left, ans);
    }
    if (node->right) {
        leafNodes(node->right, ans);
    }
}

vector<int> traverseBoundary(TreeNode<int>* root) {
    vector<int> ans;
    if (root == NULL) return ans;

    if (!isLeaf(root)) {
        ans.push_back(root->data);  
    }

    leftBoundary(root->left, ans);
    leafNodes(root, ans);
    rightBoundary(root->right, ans);

    return ans;
}
157 views
0 replies
0 upvotes

Interview problems

JAVA SOLUTION || Boundary Traversal of Binary Tree ||

import java.util.*;

public class Solution {

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

        List<Integer> boundary = new ArrayList<>();

        if (root != null) {

            boundary.add(root.data);

            leftBoundary(root.left, boundary);

            leafNodes(root, boundary);

            rightBoundary(root.right, boundary);

        }

        return boundary;

    }    

    private static void leftBoundary(TreeNode node, List<Integer> boundary) {

        if (node != null) {

            if (node.left != null || node.right != null) {

                boundary.add(node.data);

                if (node.left != null) {

                    leftBoundary(node.left, boundary);

                } else {

                    leftBoundary(node.right, boundary);

                }

            }

        }

    }

    private static void rightBoundary(TreeNode node, List<Integer> boundary) {

        if (node != null) {

            if (node.left != null || node.right != null) {

                if (node.right != null) {

                    rightBoundary(node.right, boundary);

                } else {

                    rightBoundary(node.left, boundary);

                }

                boundary.add(node.data);

            }

        }

    }

    private static void leafNodes(TreeNode node, List<Integer> boundary) {

        if (node != null) {

            leafNodes(node.left, boundary);

            if (node.left == null && node.right == null) {

                boundary.add(node.data);

            }

            leafNodes(node.right, boundary);

        }

    }

}

38 views
0 replies
0 upvotes

Interview problems

c++ simple easy solution

vector<int> insertLeftBoundary(TreeNode<int>* root, vector<int>& ans) {

    if (root == nullptr || (!root->left && !root->right)) return ans;

    ans.push_back(root->data);

    if (root->left) insertLeftBoundary(root->left, ans);

    else insertLeftBoundary(root->right, ans);

    return ans;

}

 

vector<int> insertLeaves(TreeNode<int>* root, vector<int>& ans) {

    if (root == nullptr) return ans;

    if (!root->left && !root->right) ans.push_back(root->data);

    insertLeaves(root->left, ans);

    insertLeaves(root->right, ans);

    return ans;

}

 

vector<int> insertRightBoundary(TreeNode<int>* root, vector<int>& ans) {

    if (root == nullptr || (!root->left && !root->right)) return ans;

    if (root->right) insertRightBoundary(root->right, ans);

    else insertRightBoundary(root->left, ans);

    ans.push_back(root->data);

    return ans;

}

 

vector<int> traverseBoundary(TreeNode<int>* root) {

    vector<int> ans;

    if (root == nullptr) return ans;

    ans.push_back(root->data);

    insertLeftBoundary(root->left, ans);

    insertLeaves(root->left, ans);

    insertLeaves(root->right, ans);

    insertRightBoundary(root->right, ans);

    return ans;

}

145 views
0 replies
0 upvotes

Interview problems

Missing Test Case

1

19 views
0 replies
0 upvotes

Interview problems

100%solution using recursion

void traverseLeft(TreeNode<int> *root,vector<int>& ans){

    //base case

    // leave leaf node

    if((root==NULL)|| (root->left==NULL && root->right==NULL) ){

        return ;

    }

    ans.push_back(root->data);

 

    if(root->left) traverseLeft(root->left, ans);

    else traverseLeft(root->right, ans);

}

void traverseLeaf(TreeNode<int> *root,vector<int>& ans){

    if(root==NULL) return;

    if(root->left==NULL && root->right==NULL){

        ans.push_back(root->data);

    }

    traverseLeaf(root->left, ans);

    traverseLeaf(root->right, ans);

}

void traverseRight(TreeNode<int> *root,vector<int>& ans){

    //base case

    // leave leaf node

    if((root==NULL)|| (root->left==NULL && root->right==NULL) ){

        return ;

    }

 

    if(root->right) traverseRight(root->right, ans);

    else traverseRight(root->left, ans);

    ans.push_back(root->data);

}

vector<int> traverseBoundary(TreeNode<int> *root)

{

    vector<int>ans;

    //base case

    if(root==NULL)

    return ans;

 

    ans.push_back(root->data);

    //left part

    traverseLeft(root->left,ans);

 

    //left subtree leaf

    traverseLeaf(root->left,ans);

 

    //right subtree leaf

    traverseLeaf(root->right,ans);

 

    //right part

    traverseRight(root->right,ans);

 

    return ans;

}

148 views
1 reply
0 upvotes

Interview problems

EASY AND OPTIMAL SOLUTION.

EASY AND OPTIMAL SOLUTION. JUST YOU NEED TO TRAVERSE 1. LEFT PART 2. LEAVE NODES 3. RIGHT PART(EXCLUDING ROOT) 4. REVERSE THE RIGHT PART 5. RETURN THE FINAL RESULT VECTOR)

63 views
0 replies
0 upvotes
Full screen
Console