Tutorialspoint.dev

Path length having maximum number of bends

Given a binary tree, find the path length having maximum number of bends.
Note : Here, bend indicates switching from left to right or vice versa while traversing in the tree.
For example, consider below paths (L means moving leftwards, R means moving rightwards):
LLRRRR – 1 Bend
RLLLRR – 2 Bends
LRLRLR – 5 Bends

Prerequisite : Finding Max path length in a Binary Tree

Examples:

Input : 
            4
          /   
        2      6
      /      / 
    1     3  5   7
                /
               9
              / 
             12 10
                  
                  11
                  / 
                45  13
                      
                      14

Output : 6
In the above example, the path 4-> 6-> 7-> 9-> 10-> 11-> 45
is having the maximum number of bends, i.e., 3. 
The length of this path is 6. 



Approach :
The idea is to traverse the tree for left and right subtrees of the root. While traversing, keep track of the direction of motion (left or right). Whenever, direction of motion changes from left to right or vice versa increment the number of bends in the current path by 1.
On reaching the leaf node, compare the number of bends in the current path with the maximum number of bends(i.e., maxBends) seen so far in a root-to-leaf path. If the number of bends in the current path is greater than the maxBends, then update the maxBends equal to the number of bends in the current path and update the maximum path length (i.e., len) also to the length of the current path.

Implementation :

C++

// C++ program to find path length
// having maximum number of bends
#include <bits/stdc++.h>
using namespace std;
  
// structure node
struct Node {
    int key;
    struct Node* left;
    struct Node* right;
};
  
// Utility function to create a new node
struct Node* newNode(int key)
{
    struct Node* node = new Node();
    node->left = NULL;
    node->right = NULL;
    node->key = key;
  
    return node;
}
  
/* Recursive function to calculate the path
length having maximum number of bends.
The following are parameters for this function.
  
node --> pointer to the current node
dir --> determines whether the current node
is left or right child of it's parent node
bends --> number of bends so far in the
current path.
maxBends --> maximum number of bends in a
path from root to leaf
soFar --> length of the current path so
far traversed
len --> length of the path having maximum
number of bends
*/
void findMaxBendsUtil(struct Node* node,
                      char dir, int bends,
                      int* maxBends, int soFar,
                      int* len)
{
    // Base Case
    if (node == NULL)
        return;
  
    // Leaf node
    if (node->left == NULL && node->right == NULL) {
        if (bends > *maxBends) {
            *maxBends = bends;
            *len = soFar;
        }
    }
  
    // Left child is NULL
    else if (node->left == NULL) {
        if (dir == 'r') {
            findMaxBendsUtil(node->right, dir,
                             bends, maxBends,
                             soFar + 1, len);
        }
        else {
            findMaxBendsUtil(node->right, 'r',
                             bends + 1, maxBends,
                             soFar + 1, len);
        }
    }
  
    // Right child is NULL
    else if (node->right == NULL) {
        if (dir == 'l') {
            findMaxBendsUtil(node->left, dir,
                             bends, maxBends,
                             soFar + 1, len);
        }
        else {
            findMaxBendsUtil(node->left, 'l',
                             bends + 1, maxBends,
                             soFar + 1, len);
        }
    }
    // Having both left and right child
    else {
        if (dir == 'l') {
            findMaxBendsUtil(node->left, dir,
                             bends, maxBends,
                             soFar + 1, len);
            findMaxBendsUtil(node->right, 'r',
                             bends + 1, maxBends,
                             soFar + 1, len);
        }
        else {
            findMaxBendsUtil(node->right, dir,
                             bends, maxBends,
                             soFar + 1, len);
            findMaxBendsUtil(node->left, 'l',
                             bends + 1, maxBends,
                             soFar + 1, len);
        }
    }
}
  
// Helper function to call findMaxBendsUtil()
int findMaxBends(struct Node* node)
{
    if (node == NULL)
        return 0;
  
    int len = 0, bends = 0, maxBends = -1;
  
    // Call for left subtree of the root
    if (node->left)
        findMaxBendsUtil(node->left, 'l',
                         bends, &maxBends, 1, &len);
  
    // Call for right subtree of the root
    if (node->right)
        findMaxBendsUtil(node->right, 'r', bends,
                         &maxBends, 1, &len);
  
    // Include the root node as well in the path length
    len++;
  
    return len;
}
  
// Driver code
int main()
{
    /* Constructed binary tree is
      10
      /
     8    2
    /   /
    3  5 2
          
           1
          /
         9
    */
  
    struct 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);
    root->right->left->right = newNode(1);
    root->right->left->right->left = newNode(9);
  
    cout << findMaxBends(root) - 1;
  
    return 0;
}

Python3

# Python3 program to find path Length
# having maximum number of bends

# Utility function to create a new node
class newNode:
def __init__(self, key):
self.left = None
self.right = None
self.key = key

# Recursive function to calculate the path
# Length having maximum number of bends.
# The following are parameters for this function.

# node -. pointer to the current node
# Dir -. determines whether the current node
# is left or right child of it’s parent node
# bends -. number of bends so far in the
# current path.
# maxBends -. maximum number of bends in a
# path from root to leaf
# soFar -. Length of the current path so
# far traversed
# Len -. Length of the path having maximum
# number of bends

def findMaxBendsUtil(node, Dir, bends,
maxBends, soFar, Len):

# Base Case
if (node == None):
return

# Leaf node
if (node.left == None and
node.right == None):
if (bends > maxBends[0]):
maxBends[0] = bends
Len[0] = soFar

# Left child is None
elif (node.left == None):
if (Dir == ‘r’):
findMaxBendsUtil(node.right, Dir, bends,
maxBends, soFar + 1, Len)
else:
findMaxBendsUtil(node.right, ‘r’, bends + 1,
maxBends, soFar + 1, Len)

# Right child is None
elif (node.right == None):
if (Dir == ‘l’):
findMaxBendsUtil(node.left, Dir, bends,
maxBends, soFar + 1, Len)
else:
findMaxBendsUtil(node.left, ‘l’, bends + 1,
maxBends, soFar + 1, Len)

# Having both left and right child
else:
if (Dir == ‘l’):
findMaxBendsUtil(node.left, Dir, bends,
maxBends, soFar + 1, Len)
findMaxBendsUtil(node.right, ‘r’, bends + 1,
maxBends, soFar + 1, Len)
else:
findMaxBendsUtil(node.right, Dir, bends,
maxBends, soFar + 1, Len)
findMaxBendsUtil(node.left, ‘l’, bends + 1,
maxBends, soFar + 1, Len)

# Helper function to call findMaxBendsUtil()
def findMaxBends(node):
if (node == None):
return 0

Len = [0]
bends = 0
maxBends = [-1]

# Call for left subtree of the root
if (node.left):
findMaxBendsUtil(node.left, ‘l’, bends,
maxBends, 1, Len)

# Call for right subtree of the root
if (node.right):
findMaxBendsUtil(node.right, ‘r’, bends,
maxBends, 1, Len)

# Include the root node as well
# in the path Length
Len[0] += 1

return Len[0]

# Driver code
if __name__ == ‘__main__’:

# Constructed binary tree is
# 10
# /
# 8 2
# / /
# 3 5 2
#
# 1
# /
# 9
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)
root.right.left.right = newNode(1)
root.right.left.right.left = newNode(9)

print(findMaxBends(root) – 1)

# This code is contributed by PranchalK


Output:

4


This article is attributed to GeeksforGeeks.org

tags:

Tree Tree

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter