Open In App

Print root to leaf paths without using recursion

Last Updated : 24 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary tree, print all its root-to-leaf paths without using recursion. For example, consider the following Binary Tree. 

        6
     /    \
    3      5
  /   \     \
 2     5     4
     /   \
    7     4

There are 4 leaves, hence 4 root to leaf paths -
  6->3->2              
  6->3->5->7
  6->3->5->4
  6->5>4

We strongly recommend you to minimize your browser and try this yourself first.

We can traverse tree iteratively (we have used iterative preorder). The question is, how to extend the traversal to print root-to-leaf paths? The idea is to maintain a map to store parent pointers of binary tree nodes. Now whenever we encounter a leaf node while doing iterative preorder traversal, we can easily print root to leaf path using parent pointer. 

Below is the implementation of this idea.

C++




// C++ program to Print root to leaf path WITHOUT
// using recursion
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree */
struct Node
{
    int data;
    struct Node *left, *right;
};
 
/* Helper function that allocates a new node
   with the given data and NULL left and right
   pointers.*/
Node* newNode(int data)
{
    Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return node;
}
 
/* Function to print root to leaf path for a leaf
   using parent nodes stored in map */
void printTopToBottomPath(Node* curr,
                         map<Node*, Node*> parent)
{
    stack<Node*> stk;
 
    // start from leaf node and keep on pushing
    // nodes into stack till root node is reached
    while (curr)
    {
        stk.push(curr);
        curr = parent[curr];
    }
 
    // Start popping nodes from stack and print them
    while (!stk.empty())
    {
        curr = stk.top();
        stk.pop();
        cout << curr->data << " ";
    }
    cout << endl;
}
 
/* An iterative function to do preorder traversal
   of binary tree  and print root to leaf path
   without using recursion */
void printRootToLeaf(Node* root)
{
    // Corner Case
    if (root == NULL)
        return;
 
    // Create an empty stack and push root to it
    stack<Node*> nodeStack;
    nodeStack.push(root);
 
    // Create a map to store parent pointers of binary
    // tree nodes
    map<Node*, Node*> parent;
 
    // parent of root is NULL
    parent[root] = NULL;
 
    /* Pop all items one by one. Do following for
       every popped item
        a) push its right child and set its parent
           pointer
        b) push its left child and set its parent
           pointer
       Note that right child is pushed first so that
       left is processed first */
    while (!nodeStack.empty())
    {
        // Pop the top item from stack
        Node* current = nodeStack.top();
        nodeStack.pop();
 
        // If leaf node encountered, print Top To
        // Bottom path
        if (!(current->left) && !(current->right))
            printTopToBottomPath(current, parent);
 
        // Push right & left children of the popped node
        // to stack. Also set their parent pointer in
        // the map
        if (current->right)
        {
            parent[current->right] = current;
            nodeStack.push(current->right);
        }
        if (current->left)
        {
            parent[current->left] = current;
            nodeStack.push(current->left);
        }
    }
}
 
// Driver program to test above functions
int main()
{
    /* Constructed binary tree is
         10
        /  \
       8    2
      / \   /
     3     5 2     */
    Node* root = newNode(10);
    root->left = newNode(8);
    root->right = newNode(2);
    root->left->left = newNode(3);
    root->left->right = newNode(5);
    root->right->left = newNode(2);
 
    printRootToLeaf(root);
 
    return 0;
}


Java




// Java program to Print root to leaf path WITHOUT
// using recursion
import java.util.Stack;
import java.util.HashMap;
public class PrintPath {
 
    /* Function to print root to leaf path for a leaf
    using parent nodes stored in map */
    public static void printTopToBottomPath(Node curr, HashMap<Node,Node> parent)
    {
        Stack<Node> stk=new Stack<>() ;
   
        // start from leaf node and keep on pushing
        // nodes into stack till root node is reached
        while (curr!=null)
        {
            stk.push(curr);
            curr = parent.get(curr);
        }
   
        // Start popping nodes from stack and print them
        while (!stk.isEmpty())
        {
            curr = stk.pop();
            System.out.print(curr.data+" ");
        }
        System.out.println();
    }
 
 
    /* An iterative function to do preorder traversal
    of binary tree  and print root to leaf path
    without using recursion */
    public static void printRootToLeaf(Node root)
    {
        // Corner Case
        if (root == null)
            return;
   
        // Create an empty stack and push root to it
        Stack<Node> nodeStack=new Stack<>();
        nodeStack.push(root);
   
        // Create a map to store parent pointers of binary
        // tree nodes
        HashMap<Node,Node> parent=new HashMap<>();
   
        // parent of root is NULL
        parent.put(root,null);
   
        /* Pop all items one by one. Do following for
        every popped item
            a) push its right child and set its parent
            pointer
            b) push its left child and set its parent
            pointer
        Note that right child is pushed first so that
        left is processed first */
        while (!nodeStack.isEmpty())
        {
            // Pop the top item from stack
            Node current = nodeStack.pop();
   
            // If leaf node encountered, print Top To
            // Bottom path
            if (current.left==null && current.right==null)
                printTopToBottomPath(current, parent);
   
            // Push right & left children of the popped node
            // to stack. Also set their parent pointer in
            // the map
            if (current.right!=null)
            {
                parent.put(current.right,current);
                nodeStack.push(current.right);
            }
            if (current.left!=null)
            {
                parent.put(current.left,current);
                nodeStack.push(current.left);
            }
        }
    }
 
 
    public static void main(String args[]) {
        Node root=new Node(10);
        root.left = new Node(8);
        root.right = new Node(2);
        root.left.left = new Node(3);
        root.left.right = new Node(5);
        root.right.left = new Node(2);
        printRootToLeaf(root);
    }
}
 
/* A binary tree node */
class Node
{
    int data;
    Node left, right;
    Node(int data)
    {
        left=right=null;
        this.data=data;
    }
};
//This code is contributed by Gaurav Tiwari


Python3




# Python3 program to Print root to
# leaf path without using recursion
 
# Helper function that allocates a new
# node with the given data and None left
# and right pointers.
class newNode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
# Function to print root to leaf path for a
# leaf using parent nodes stored in map
def printTopToBottomPath(curr, parent):
    stk = []
 
    # start from leaf node and keep on appending
    # nodes into stack till root node is reached
    while (curr):
        stk.append(curr)
        curr = parent[curr]
 
    # Start popping nodes from stack
    # and print them
    while len(stk) != 0:
        curr = stk[-1]
        stk.pop(-1)
        print(curr.data, end = " ")
    print()
 
# An iterative function to do preorder
# traversal of binary tree and print
# root to leaf path without using recursion
def printRootToLeaf(root):
     
    # Corner Case
    if (root == None):
        return
 
    # Create an empty stack and
    # append root to it
    nodeStack = []
    nodeStack.append(root)
 
    # Create a map to store parent
    # pointers of binary tree nodes
    parent = {}
 
    # parent of root is None
    parent[root] = None
 
    # Pop all items one by one. Do following
    # for every popped item
    # a) append its right child and set its 
    #     parent pointer
    # b) append its left child and set its
    #     parent pointer
    # Note that right child is appended first
    # so that left is processed first
    while len(nodeStack) != 0:
         
        # Pop the top item from stack
        current = nodeStack[-1]
        nodeStack.pop(-1)
 
        # If leaf node encountered, print
        # Top To Bottom path
        if (not (current.left) and
            not (current.right)):
            printTopToBottomPath(current, parent)
 
        # append right & left children of the
        # popped node to stack. Also set their
        # parent pointer in the map
        if (current.right):
            parent[current.right] = current
            nodeStack.append(current.right)
        if (current.left):
            parent[current.left] = current
            nodeStack.append(current.left)
 
# Driver Code
if __name__ == '__main__':
     
    # Constructed binary tree is
    #     10
    # / \
    # 8 2
    # / \ /
    # 3 5 2    
    root = newNode(10)
    root.left = newNode(8)
    root.right = newNode(2)
    root.left.left = newNode(3)
    root.left.right = newNode(5)
    root.right.left = newNode(2)
 
    printRootToLeaf(root)
     
# This code is contributed by PranchalK


C#




// C# program to Print root to leaf path WITHOUT
// using recursion
using System;
using System.Collections.Generic;
 
public class PrintPath
{
 
    /* Function to print root to leaf path for a leaf
    using parent nodes stored in map */
    public static void printTopToBottomPath(Node curr,
                        Dictionary<Node,Node> parent)
    {
        Stack<Node> stk = new Stack<Node>() ;
     
        // start from leaf node and keep on pushing
        // nodes into stack till root node is reached
        while (curr != null)
        {
            stk.Push(curr);
            curr = parent[curr];
        }
     
        // Start popping nodes from stack and print them
        while (stk.Count != 0)
        {
            curr = stk.Pop();
            Console.Write(curr.data + " ");
        }
        Console.WriteLine();
    }
 
 
    /* An iterative function to do preorder traversal
    of binary tree and print root to leaf path
    without using recursion */
    public static void printRootToLeaf(Node root)
    {
        // Corner Case
        if (root == null)
            return;
     
        // Create an empty stack and push root to it
        Stack<Node> nodeStack = new Stack<Node>();
        nodeStack.Push(root);
     
        // Create a map to store parent 
        // pointers of binary tree nodes
        Dictionary<Node,Node> parent = new Dictionary<Node,Node>();
     
        // parent of root is NULL
        parent.Add(root, null);
     
        /* Pop all items one by one. Do following for
        every popped item
            a) push its right child and set its parent
            pointer
            b) push its left child and set its parent
            pointer
        Note that right child is pushed first so that
        left is processed first */
        while (nodeStack.Count != 0)
        {
            // Pop the top item from stack
            Node current = nodeStack.Pop();
     
            // If leaf node encountered, print Top To
            // Bottom path
            if (current.left == null && current.right == null)
                printTopToBottomPath(current, parent);
     
            // Push right & left children of the popped node
            // to stack. Also set their parent pointer in
            // the map
            if (current.right != null)
            {
                parent.Add(current.right,current);
                nodeStack.Push(current.right);
            }
            if (current.left != null)
            {
                parent.Add(current.left,current);
                nodeStack.Push(current.left);
            }
        }
    }
 
    // Driver code
    public static void Main(String []args)
    {
        Node root = new Node(10);
        root.left = new Node(8);
        root.right = new Node(2);
        root.left.left = new Node(3);
        root.left.right = new Node(5);
        root.right.left = new Node(2);
        printRootToLeaf(root);
    }
}
 
/* A binary tree node */
public class Node
{
    public int data;
    public Node left, right;
    public Node(int data)
    {
        left = right = null;
        this.data = data;
    }
};
 
// This code is contributed Rajput-Ji


Javascript




<script>
  
// Javascript program to Print root to leaf path WITHOUT
// using recursion
 
/* Function to print root to leaf path for a leaf
using parent nodes stored in map */
function printTopToBottomPath(curr, parent)
{
    var stk = [];
 
    // start from leaf node and keep on pushing
    // nodes into stack till root node is reached
    while (curr != null)
    {
        stk.push(curr);
        curr = parent.get(curr);
    }
 
    // Start popping nodes from stack and print them
    while (stk.length != 0)
    {
        curr = stk[stk.length-1];
        stk.pop();
        document.write(curr.data + " ");
    }
    document.write("<br>");
}
/* An iterative function to do preorder traversal
of binary tree and print root to leaf path
without using recursion */
function printRootToLeaf(root)
{
    // Corner Case
    if (root == null)
        return;
 
    // Create an empty stack and push root to it
    var nodeStack = [];
    nodeStack.push(root);
 
    // Create a map to store parent 
    // pointers of binary tree nodes
    var parent = new Map();
 
    // parent of root is NULL
    parent.set(root, null);
 
    /* pop all items one by one. Do following for
    every popped item
        a) push its right child and set its parent
        pointer
        b) push its left child and set its parent
        pointer
    Note that right child is pushed first so that
    left is processed first */
    while (nodeStack.length != 0)
    {
        // pop the top item from stack
        var current = nodeStack[nodeStack.length-1];
        nodeStack.pop();
 
        // If leaf node encountered, print Top To
        // Bottom path
        if (current.left == null && current.right == null)
            printTopToBottomPath(current, parent);
 
        // push right & left children of the popped node
        // to stack. Also set their parent pointer in
        // the map
        if (current.right != null)
        {
            parent.set(current.right,current);
            nodeStack.push(current.right);
        }
        if (current.left != null)
        {
            parent.set(current.left,current);
            nodeStack.push(current.left);
        }
    }
}
 
/* binary tree node */
class Node
{
  constructor(data)
  {
    this.left = null;
    this.data = data;
    this.right = null;
  }
}
 
// Driver code
var root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);
printRootToLeaf(root);
 
// This code is contributed by itsok.
</script>


Output

10 8 3 
10 8 5 
10 2 2 

Time Complexity: O(n log(n)), where n is the total nodes in binary tree.
Auxiliary Space: O(n).

Another Approach:

This method is an optimization of the previous one. The problem can be solved without maintaining a parent pointer or the use of any additional extra space other than stack. We can store the path from root to leaf in a string as we traverse iteratively and print the path as soon as we encounter any leaf node.

Below is the implementation of above idea.

C++




// C++ program to print root to leaf path without using
// recursion
#include <bits/stdc++.h>
using namespace std;
 
// A binary tree node structure
struct Node {
    int data;
    Node *left, *right;
};
 
// fun to create a new node
Node* newNode(int data)
{
    Node* temp = new Node();
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// fun to check leaf node
bool isleafnode(Node* root)
{
    return !root->left && !root->right;
}
 
// fun to print root to leaf paths without using parent
// pointers
void printRootToLeaf(Node* root)
{
    // base case
    if (!root)
        return;
 
    string path = "";
 
    // create an empty stack to store a pair of tree nodes
    // and its path from root node.
    stack<pair<Node*, string> > s;
 
    // push the root node
    s.push({ root, path });
 
    // loop until stack becomes empty
    while (!s.empty()) {
 
        auto it = s.top();
        s.pop();
 
        root = it.first;
        path = it.second;
 
        // convert the curr root value to string
        string curr = to_string(root->data) + " ";
 
        // add the current node to the existing path
        path += curr;
 
        // print the path if a node is encountered
        if (isleafnode(root))
            cout << path << endl;
 
        if (root->right)
            s.push({ root->right, path });
        if (root->left)
            s.push({ root->left, path });
    }
}
 
int main()
{
    // create a tree
    Node* root = newNode(10);
    root->left = newNode(8);
    root->right = newNode(2);
    root->left->left = newNode(3);
    root->left->right = newNode(5);
    root->right->left = newNode(2);
 
    printRootToLeaf(root);
 
    return 0;
}
// This code is contributed by Modem Upendra


Java




// Java program to print root to leaf path without using
// recursion
import java.util.*;
 
public class GFG {
 
  // A binary tree node structure
  static class Node {
    int data;
    Node left, right;
 
    // fun to create a new node
    Node(int data)
    {
      this.data = data;
      this.left = this.right = null;
    }
  };
 
  // fun to check leaf node
  static boolean isleafnode(Node root)
  {
    return root.left == null && root.right == null;
  }
 
  static class pair {
    Node first;
    String second;
    pair(Node f, String s)
    {
      first = f;
      second = new String(s);
    }
  }
 
  // fun to print root to leaf paths without using parent
  // pointers
  static void printRootToLeaf(Node root)
  {
    // base case
    if (root == null)
      return;
 
    String path = "";
 
    // create an empty stack to store a pair of tree
    // nodes and its path from root node.
    Stack<pair> s = new Stack<>();
 
    // push the root node
    s.push(new pair(root, path));
 
    // loop until stack becomes empty
    while (!s.isEmpty()) {
 
      pair it = s.peek();
      s.pop();
 
      root = it.first;
      path = it.second;
 
      // convert the curr root value to string
      String curr = (root.data) + " ";
 
      // add the current node to the existing path
      path += curr;
 
      // print the path if a node is encountered
      if (isleafnode(root))
        System.out.println(path);
 
      if (root.right != null)
        s.push(new pair(root.right, path));
      if (root.left != null)
        s.push(new pair(root.left, path));
    }
  }
 
  public static void main(String[] args)
  {
    // create a tree
    Node root = new Node(10);
    root.left = new Node(8);
    root.right = new Node(2);
    root.left.left = new Node(3);
    root.left.right = new Node(5);
    root.right.left = new Node(2);
 
    printRootToLeaf(root);
  }
}
 
// This code is contributed by Karandeep1234


Python3




# Python program to print root to leaf path without using
# recursion
 
# A binary tree node structure
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# fun to create a new node
def newNode(data):
    temp = Node(data)
    return temp
 
# fun to check leaf node
def isleafnode(root):
    return not root.left and not root.right
 
# fun to print root to leaf paths without using parent
# pointers
def printRootToLeaf(root):
    # base case
    if not root:
        return
 
    path = ""
 
    # create an empty stack to store a pair of tree nodes
    # and its path from root node.
    s = []
 
    # push the root node
    s.append((root, path))
 
    # loop until stack becomes empty
    while len(s) > 0:
        it = s.pop()
        root = it[0]
        path = it[1]
 
        # convert the curr root value to string
        curr = str(root.data) + " "
 
        # add the current node to the existing path
        path += curr
 
        # print the path if a node is encountered
        if isleafnode(root):
            print(path)
 
        if root.right:
            s.append((root.right, path))
        if root.left:
            s.append((root.left, path))
 
# create a tree
root = newNode(10)
root.left = newNode(8)
root.right = newNode(2)
root.left.left = newNode(3)
root.left.right = newNode(5)
root.right.left = newNode(2)
 
printRootToLeaf(root)


C#




// C# program to print root to leaf path without using
// recursion
using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG {
 
    // A binary tree node structure
    class Node {
        public int data;
        public Node left, right;
        public Node(int data)
        {
            left = right = null;
            this.data = data;
        }
    }
     
    // fun to check leaf node
    static bool isleafnode(Node root)
    {
        return root.left==null && root.right==null;
    }
     
    // fun to print root to leaf paths without using parent
    // pointers
    static void printRootToLeaf(Node root)
    {
        // base case
        if (root==null)
            return;
     
        string path = "";
     
        // create an empty stack to store a pair of tree nodes
        // and its path from root node.
        Stack<Tuple<Node, string> > s=new Stack<Tuple<Node, string>>();
     
        // push the root node
        s.Push(Tuple.Create(root, path));
     
        // loop until stack becomes empty
        while (s.Count>0) {
     
            Tuple<Node, string> it = s.Peek();
            s.Pop();
     
            root = it.Item1;
            path = it.Item2;
     
            // convert the curr root value to string
            string curr = root.data.ToString() + " ";
     
            // add the current node to the existing path
            path += curr;
     
            // print the path if a node is encountered
            if (isleafnode(root))
                Console.WriteLine(path);
     
            if (root.right!=null)
                s.Push(Tuple.Create(root.right, path));
            if (root.left!=null)
                s.Push(Tuple.Create(root.left, path));
        }
    }
     
    public static void Main (string[] args)
    {
        // create a tree
        Node root = new Node(10);
        root.left = new Node(8);
        root.right = new Node(2);
        root.left.left = new Node(3);
        root.left.right = new Node(5);
        root.right.left = new Node(2);
     
        printRootToLeaf(root);
    }
}


Javascript




// JavaScript program to print root to leaf path without using recursion
 
// A binary tree node structure
class Node{
    constructor(data){
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
 
class pair{
    constructor(val1, val2){
        this.first = val1;
        this.second = val2;
    }
}
 
// function to create a new node
function newNode(data){
    let temp = new Node(data);
    return temp;
}
 
// function to check leaf node
function isleafnode(root){
    if(root.left == null && root.right == null) return true;
    return false;
}
 
// function to print root to leaf paths without using parent
// pointers
function printRootToLeaf(root){
    // base case
    if(root == null) return;
     
    let path = "";
     
    // create an empty stack to store a pair of tree nodes
    // and its path from root node.
    let s = [];
     
    // push the root node
    s.push(new pair(root, path));
    // loop until stack becomes empty
    while(s.length > 0){
        let it = s.pop();
         
        root = it.first;
        path = it.second;
         
        // convert the curr root value to string
        let curr = (root.data).toString() + " ";
         
        // add the current node to the existing path
        path = path + curr;
         
        // print the path if a node is encountered
        if(isleafnode(root))
            console.log(path);
         
        if(root.right != null)
            s.push(new pair(root.right, path));
        if(root.left != null)
            s.push(new pair(root.left, path));
    }
}
 
// create a tree
let root = newNode(10);
root.left = newNode(8);
root.right = newNode(2);
root.left.left = newNode(3);
root.left.right = newNode(5);
root.right.left = newNode(2);
 
printRootToLeaf(root);
 
// This code is contributed by Yash Agarwal


Output

10 8 3 
10 8 5 
10 2 2 

Time Complexity: O(n), where n refers to total nodes in a binary tree.
Auxiliary Space: O(n).



Previous Article
Next Article

Similar Reads

Given a binary tree, print out all of its root-to-leaf paths one per line.
Given the roots of a tree. print out all of its root-to-leaf paths one per line.. Algorithm: initialize: pathlen = 0, path[1000] /*1000 is some max limit for paths, it can change*/ /*printPathsRecur traverses nodes of tree in preorder */ printPathsRecur(tree, path[], pathlen) 1) If node is not NULL then a) push data to path array: path[pathlen] = n
9 min read
Print all the root-to-leaf paths of a Binary Tree whose XOR is non-zero
Given a Binary Tree, the task is to print all root-to-leaf paths of this tree whose xor value is non-zero. Examples: Input: 10 / \ 10 3 / \ 10 3 / \ / \ 7 3 42 13 / 7 Output: 10 3 10 7 10 3 3 42 Explanation: All the paths in the given binary tree are : {10, 10} xor value of the path is = 10 ^ 10 = 0 {10, 3, 10, 7} xor value of the path is = 10 ^ 3
11 min read
Print all root-to-leaf paths with maximum count of even nodes
Given a Binary tree, the task is to print all possible root-to-leaf paths having a maximum number of even valued nodes. Examples: Input: 2 / \ 6 3 / \ \ 4 7 11 / \ \ 10 12 1 Output: 2 -&gt; 6 -&gt; 4 -&gt; 10 2 -&gt; 6 -&gt; 4 -&gt; 12 Explanation: Count of even nodes on the path 2 -&gt; 6 -&gt; 4 -&gt; 10 = 4 Count of even nodes on the path 2 -
13 min read
Print all root to leaf paths of an N-ary tree
Given an N-Ary tree, the task is to print all root to leaf paths of the given N-ary Tree. Examples: Input: 1 / \ 2 3 / / \ 4 5 6 / \ 7 8 Output:1 2 41 3 51 3 6 71 3 6 8 Input: 1 / | \ 2 5 3 / \ \ 4 5 6Output:1 2 41 2 51 51 3 6 Approach: The idea to solve this problem is to start traversing the N-ary tree using depth-first search and keep inserting
7 min read
Print all the paths from root to leaf, with a specified sum in Binary tree
Given a Binary tree, and target sum as K, the task is to print all the possible paths from root to leaf that has the sum equal to K. Examples: Input: K = 22 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 Output: [5, 4, 11, 2] [5, 8, 4 , 5] Explanation: In the above tree, the paths [5, 4, 11, 2] and [5, 8, 4, 5] are the paths from root to a leaf which has
9 min read
Given a binary tree, print all root-to-leaf paths
For the below example tree, all root-to-leaf paths are: 10 –&gt; 8 –&gt; 3 10 –&gt; 8 –&gt; 5 10 –&gt; 2 –&gt; 2 Recommended PracticeRoot to Leaf PathsTry It! Algorithm: Use a path array path[] to store current root to leaf path. Traverse from root to all leaves in top-down fashion. While traversing, store data of all nodes in current path in array
15+ min read
Print all root to leaf paths with there relative positions
Given a binary tree, print the root to the leaf path, but add "_" to indicate the relative position. Example: Input : Root of below tree A / \ B C / \ / \ D E F G Output : All root to leaf paths _ _ A _ B D _ A B _ E A _ C F A _ C _ _ G Asked In: Google Interview The idea base on print path in vertical order. Below is complete algorithm : We do Pre
11 min read
Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K
Given an Acyclic Undirected Graph in the form of a Binary Tree with the root at vertex 1 and values at each vertex [1, N] denoted by the array arr[], the task is to find the number of root to leaf paths that contain at most m consecutive nodes with value K. Example: Input: arr[] = {1, 0, 1, 0, 0, 1, 0}, K = 1, M = 2 Output: 3 Explanation: Path 1 :
8 min read
Count the number of paths from root to leaf of a Binary tree with given XOR value
Given a value K and a binary tree, we have to find out the total number of paths from the root to leaf nodes having XOR of all its nodes along the path equal to K.Examples: Input: K = 6 2 / \ 1 4 / \ 10 5 Output: 2 Explanation: Subtree 1: 2 \ 4 This particular path has 2 nodes, 2 and 4 and (2 xor 4) = 6. Subtree 2: 2 / 1 \ 5 This particular path ha
8 min read
Count of root to leaf paths whose permutation is palindrome in a Binary Tree
Given a binary tree where node contains characters, the task is to count the number of paths from root vertex to leaf such that at least one permutation of the node values in the path is a palindrome.Examples: Input: 2 / \ 3 1 / \ \ 3 4 2 / \ / \ 2 1 2 1 Output: 2 Explanation: Paths whose one of the permutation are palindrome are - 2 =&gt; 3 =&gt;
7 min read
Article Tags :
Practice Tags :