Length of longest straight path from a given Binary Tree

Given a Binary Tree, the task is to find the length of the longest straight path of the given binary tree.
Straight Path is defined as the path that starts from any node and ends at another node in the tree such that the direction of traversal from the source node to the destination node always remains the same i.e., either left or right, without any change in direction that is left->left ->left or right->right->right direction.Â
Examples:
Input:
Output: 2
Explanation:
The path shown in green is the longest straight path from 4 to 6 which is of length 2.Â
Â
Input:
Output: 3
Explanation:
The path shown in green is the longest straight path from 5 to 0 which is of length 3.Â
Â
Approach: The idea is to use the Postorder traversal. Follow the steps below to solve the problem:
- For each node, check the direction of the current Node (either left or right) and check which direction of its child is providing the longest length below it to that node.
- If the direction of the current node and the child giving the longest length is not the same then save the result of that child and pass the length of the other child to its parent.
- Using the above steps find the longest straight path at each node and save the result to print the maximum value among all the straight paths.
- Print the maximum path after the above steps.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Structure of a Tree nodestruct Node {Â Â Â Â int key;Â Â Â Â struct Node *left, *right;};Â
// Function to create a new nodeNode* newNode(int key){Â Â Â Â Node* temp = new Node;Â Â Â Â temp->key = key;Â Â Â Â temp->left = temp->right = NULL;Â Â Â Â return (temp);}Â
// Function to find the longest// straight path in a treeint findPath(Node* root, char name,             int& max_v){    // Base Case    if (root == NULL) {        return 0;    }Â
    // Recursive call on left child    int left = findPath(root->left,                        'l', max_v);Â
    // Recursive call on right child    int right = findPath(root->right,                         'r', max_v);Â
    // Return the maximum straight    // path possible from current node    if (name == 't') {        return max(left, right);    }Â
    // Leaf node    if (left == 0 && right == 0) {        return 1;    }Â
    // Executes when either of the    // child is present or both    else {Â
        // Pass the longest value from        // either direction        if (left < right) {            if (name == 'r')                return 1 + right;Â
            else {                max_v = max(max_v, right);                return 1 + left;            }        }        else {            if (name == 'l')                return 1 + left;Â
            else {                max_v = max(max_v, left);                return 1 + right;            }        }    }    return 0;}Â
// Driver Codeint main(){Â
    // Given Tree    Node* root = newNode(3);Â
    root->left = newNode(3);    root->right = newNode(3);Â
    root->left->right = newNode(2);    root->right->left = newNode(4);    root->right->left->left = newNode(4);Â
    int max_v = max(        findPath(root, 't', max_v),        max_v);Â
    // Print the maximum length    cout << max_v << "\n";} |
Java
// Java program for the above approachimport java.util.*;Â
class GFG{Â Â Â Â Â static int max_v;Â
// Structure of a Tree nodestatic class Node{Â Â Â Â int key;Â Â Â Â Node left, right;};Â
// Function to create a new nodestatic Node newNode(int key){Â Â Â Â Node temp = new Node();Â Â Â Â temp.key = key;Â Â Â Â temp.left = temp.right = null;Â Â Â Â return (temp);}Â
// Function to find the longest// straight path in a treestatic int findPath(Node root, char name){         // Base Case    if (root == null)    {        return 0;    }Â
    // Recursive call on left child    int left = findPath(root.left, 'l');Â
    // Recursive call on right child    int right = findPath(root.right, 'r');Â
    // Return the maximum straight    // path possible from current node    if (name == 't')    {        return Math.max(left, right);    }Â
    // Leaf node    if (left == 0 && right == 0)    {        return 1;    }Â
    // Executes when either of the    // child is present or both    else    {                 // Pass the longest value from        // either direction        if (left < right)         {            if (name == 'r')                return 1 + right;            else            {                max_v = Math.max(max_v, right);                return 1 + left;            }        }        else        {            if (name == 'l')                return 1 + left;            else            {                max_v = Math.max(max_v, left);                return 1 + right;            }        }    }}Â
// Driver Codepublic static void main(String[] args){Â
    // Given Tree    Node root = newNode(3);Â
    root.left = newNode(3);    root.right = newNode(3);    root.left.right = newNode(2);    root.right.left = newNode(4);    root.right.left.left = newNode(4);Â
    max_v = Math.max(findPath(root, 't'),                     max_v);Â
    // Print the maximum length    System.out.print(max_v+ "\n");}}Â
// This code is contributed by Amit Katiyar |
Python3
# Python3 program for the above approachmax_v = 0Â
# Structure of a Tree nodeclass newNode:         def __init__(self, key):                 self.key = key        self.left = None        self.right = NoneÂ
# Function to find the longest# straight path in a treedef findPath(root, name):         global max_v         # Base Case    if (root == None):        return 0Â
    # Recursive call on left child    left = findPath(root.left, 'l')Â
    # Recursive call on right child    right = findPath(root.right, 'r')         # Return the maximum straight    # path possible from current node    if (name == 't'):        return max(left, right)Â
    # Leaf node    if (left == 0 and right == 0):        return 1Â
    # Executes when either of the    # child is present or both    else:                 # Pass the longest value from        # either direction        if (left < right):            if (name == 'r'):                return 1 + right            else:                max_v = max(max_v, right)                return 1 + left        else:            if (name == 'l'):                return 1 + left            else:                max_v = max(max_v, left)                return 1 + right                     return 0Â
def helper(root):         global max_v    temp = max(findPath(root, 't'), max_v)    print(temp)Â
# Driver Codeif __name__ == '__main__':         # Given Tree    root = newNode(3)    root.left = newNode(3)    root.right = newNode(3)    root.left.right = newNode(2)    root.right.left = newNode(4)    root.right.left.left = newNode(4)         helper(root)Â
# This code is contributed by ipg2016107 |
C#
// C# program for // the above approachusing System;class GFG{Â Â Â Â Â static int max_v;Â
// Structure of a Tree nodepublic class Node{Â Â public int key;Â Â public Node left, right;};Â
// Function to create a new nodestatic Node newNode(int key){Â Â Node temp = new Node();Â Â temp.key = key;Â Â temp.left = temp.right = null;Â Â return (temp);}Â
// Function to find the longest// straight path in a treestatic int findPath(Node root,                     char name){  // Base Case  if (root == null)  {    return 0;  }Â
  // Recursive call on left child  int left = findPath(root.left, 'l');Â
  // Recursive call on right child  int right = findPath(root.right, 'r');Â
  // Return the maximum straight  // path possible from current node  if (name == 't')  {    return Math.Max(left, right);  }Â
  // Leaf node  if (left == 0 && right == 0)  {    return 1;  }Â
  // Executes when either of the  // child is present or both  else  {    // Pass the longest value from    // either direction    if (left < right)     {      if (name == 'r')        return 1 + right;      else      {        max_v = Math.Max(max_v, right);        return 1 + left;      }    }    else    {      if (name == 'l')        return 1 + left;      else      {        max_v = Math.Max(max_v, left);        return 1 + right;      }    }  }}Â
// Driver Codepublic static void Main(String[] args){  // Given Tree  Node root = newNode(3);Â
  root.left = newNode(3);  root.right = newNode(3);  root.left.right = newNode(2);  root.right.left = newNode(4);  root.right.left.left = newNode(4);Â
  max_v = Math.Max(findPath(root, 't'), max_v);Â
  // Print the maximum length  Console.Write(max_v + "\n");}}Â
// This code is contributed by 29AjayKumar |
Javascript
       // JavaScript code for the above approach       // Structure of a Tree node       class Node {           constructor(key) {               this.key = key;               this.left = null;               this.right = null;           }       }Â
       // Function to create a new node       function newNode(key) {           const temp = new Node(key);           return temp;       }Â
       // Function to find the longest       // straight path in a tree       function findPath(root, name, maxV) {           // Base Case           if (root === null) {               return 0;           }Â
           // Recursive call on left child           const left = findPath(root.left, 'l', maxV);Â
           // Recursive call on right child           const right = findPath(root.right, 'r', maxV);Â
           // Return the maximum straight           // path possible from current node           if (name === 't') {               return Math.max(left, right);           }Â
           // Leaf node           if (left === 0 && right === 0) {               return 1;           }Â
           // Executes when either of the           // child is present or both           else {               // Pass the longest value from               // either direction               if (left < right) {                   if (name === 'r') return 1 + right;                   else {                       maxV[0] = Math.max(maxV[0], right);                       return 1 + left;                   }               } else {                   if (name === 'l') return 1 + left;                   else {                       maxV[0] = Math.max(maxV[0], left);                       return 1 + right;                   }               }           }           return 0;       }Â
       // Driver CodeÂ
       // Given Tree       const root = newNode(3);Â
       root.left = newNode(3);       root.right = newNode(3);Â
       root.left.right = newNode(2);       root.right.left = newNode(4);       root.right.left.left = newNode(4);Â
       const maxV = [0];       const maxVal = Math.max(           findPath(root, 't', maxV),           maxV[0]       );Â
       // Print the maximum length       console.log(maxVal);Â
// This code is contributed by Potta Lokesh. |
2
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!




