Open In App

Find the Root of a Tree

Last Updated : 22 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a random node of a tree, find out the root of the tree.

Note: Every node has a value (val) and a pointer (*parent) pointing towards its parent.

Examples:

Input      A                  Node : E
                / \              
              B   D                        
           / |    /  \    
        E  G  H K      
Output: A    
Explanation: A is the root of the tree

Input      1                  Node : 6
               / \            
             2   3                       
           / \    /    
        4 5   6      
Output: 1  
Explanation: 1 is the root of the tree

Approach: To solve the problem follow the below idea:

  • Traverse the tree: Start from any node in the tree and traverse upward by following parent pointers until you reach a node with no parent (i.e., the root).
  • Check node parent: In each step of the traversal, check if the current node has a parent. If it does, move to the parent node and continue the traversal.
  • Stop at the root: Repeat the traversal until you reach the root node (the node with no parent).

C++




#include<iostream>;
#include<unordered_map>;
using namespace std;
 
struct TreeNode {
    int val;
    TreeNode* parent;
    TreeNode(int value, TreeNode* p = nullptr)
        : val(value)
        , parent(p)
    {
    }
};
 
// Function to find the root of the tree
TreeNode* findRoot(TreeNode* node)
{
 
    // Traverse upward until we reach a node with no parent
    while (node!=NULL && node->parent) {
        node = node->parent;
    }
 
    return node;
}
 
int main()
{
    // Create a tree
    TreeNode* root = new TreeNode(1);
    TreeNode* node2 = new TreeNode(2, root);
    TreeNode* node3 = new TreeNode(3, root);
    TreeNode* node4 = new TreeNode(4, node2);
    TreeNode* node5 = new TreeNode(5, node2);
    TreeNode* node6 = new TreeNode(6, node3);
 
    // Find the root of the tree
    TreeNode* treeRoot = findRoot(node6);
 
    cout<<"Root value: "<<treeRoot->val<<endl;
 
    // Clean up memory
    delete node6;
    delete node5;
    delete node4;
    delete node3;
    delete node2;
    delete root;
 
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class TreeNode {
    int val;
    TreeNode parent;
 
    public TreeNode(int value, TreeNode p) {
        val = value;
        parent = p;
    }
}
 
public class Main {
    public static TreeNode findRoot(TreeNode node) {
        // Traverse upward until we reach a node with no parent
        while (node != null && node.parent != null) {
            node = node.parent;
        }
        return node;
    }
 
    public static void main(String[] args) {
        // Create a tree
        TreeNode root = new TreeNode(1, null);
        TreeNode node2 = new TreeNode(2, root);
        TreeNode node3 = new TreeNode(3, root);
        TreeNode node4 = new TreeNode(4, node2);
        TreeNode node5 = new TreeNode(5, node2);
        TreeNode node6 = new TreeNode(6, node3);
 
        // Find the root of the tree
        TreeNode treeRoot = findRoot(node6);
 
        System.out.println("Root value: " + treeRoot.val);
    }
}


Python3




class TreeNode:
    def __init__(self, value, parent=None):
        self.val = value
        self.parent = parent
 
# Function to find the root of the tree
def find_root(node):
    # Traverse upward until we reach a node with no parent
    while node is not None and node.parent is not None:
        node = node.parent
    return node
 
def main():
    # Create a tree
    root = TreeNode(1)
    node2 = TreeNode(2, root)
    node3 = TreeNode(3, root)
    node4 = TreeNode(4, node2)
    node5 = TreeNode(5, node2)
    node6 = TreeNode(6, node3)
 
    # Find the root of the tree
    tree_root = find_root(node6)
 
    print("Root value:", tree_root.val)
 
    # Clean up memory (optional in Python)
    node6 = node5 = node4 = node3 = node2 = root = None
 
if __name__ == "__main__":
    main()


C#




using System;
 
// TreeNode class representing a node in the tree
public class TreeNode
{
    public int Val { get; }
    public TreeNode Parent { get; set; }
 
    // Constructor to initialize a TreeNode with a value and optional parent
    public TreeNode(int value, TreeNode parent = null)
    {
        Val = value;
        Parent = parent;
    }
}
 
class Program
{
    // Function to find the root of the tree
    static TreeNode FindRoot(TreeNode node)
    {
        // Traverse upward until we reach a node with no parent
        while (node != null && node.Parent != null)
        {
            node = node.Parent;
        }
 
        return node;
    }
 
    static void Main()
    {
        // Create a tree
        TreeNode root = new TreeNode(1);
        // Removed node2 since it is not used
        // TreeNode node2 = new TreeNode(2, root);
        TreeNode node3 = new TreeNode(3, root);
        TreeNode node6 = new TreeNode(6, node3);
 
        // Find the root of the tree
        TreeNode treeRoot = FindRoot(node6);
 
        Console.WriteLine($"Root value: {treeRoot.Val}");
 
        // Clean up memory (assuming garbage collection in C#)
        // Note: In C#, explicit memory cleanup is often not needed due to automatic garbage collection.
        // You don't need to delete objects as you do in C++.
 
        // If you want to release resources explicitly, you can use IDisposable and implement the Dispose method.
        // For simplicity, explicit deletion is omitted in this example.
 
        // Note: C# provides automatic memory management, so there's usually no need to manually delete objects.
    }
}


Javascript




class TreeNode {
    constructor(value, parent = null) {
        this.val = value;
        this.parent = parent;
    }
}
// Function to find the root of the tree
function GFG(node) {
    // Traverse upward until we reach a node with
    // no parent
    while (node !== null && node.parent !== null) {
        node = node.parent;
    }
    return node;
}
// Main function
function main() {
    // Create a tree
    const root = new TreeNode(1);
    const node2 = new TreeNode(2, root);
    const node3 = new TreeNode(3, root);
    const node4 = new TreeNode(4, node2);
    const node5 = new TreeNode(5, node2);
    const node6 = new TreeNode(6, node3);
    // Find the root of the tree
    const treeRoot = GFG(node6);
    // Output the root value
    console.log("Root value:", treeRoot.val);
}
main();


Output

Root value: 1

Time Complexity: O(N), where N is the number of nodes
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads