Tree algo Flashcards
applications of Trees:
To represent hierarchical data.
Binary Search Trees.
Binary heap
B and B+ Trees in DBMS
Spanning and Shortest path in computer networks
Parse Tree and Expression Tree in Compilers.
implementation to represent a Binary Tree.
// Node class to represent each element in the BST class Node { int data; Node left; Node right; public Node(int data) { this.data = data; left = right = null; } }
Implementation of Inorder Traversal
#include (bits/stdc++.h> using namespace std;
struct Node { int key; struct Node *left; struct Node *right; Node(int k){ key=k; left=right=NULL; } };
void inorder(Node *root){ if(root!=NULL){ inorder(root->left); cout((root->key((" "; inorder(root->right); } }
int main() {
Node *root=new Node(10); root->left=new Node(20); root->right=new Node(30); root->right->left=new Node(40); root->right->right=new Node(50);
inorder(root); } 20 10 40 30 50
Implementation of Preorder Traversal
#include (bits/stdc++.h> using namespace std;
struct Node { int key; struct Node *left; struct Node *right; Node(int k){ key=k; left=right=NULL; } };
void preorder(Node *root){ if(root!=NULL){ cout((root->key((" "; preorder(root->left); preorder(root->right); } }
int main() {
Node *root=new Node(10); root->left=new Node(20); root->right=new Node(30); root->right->left=new Node(40); root->right->right=new Node(50);
preorder(root); } 10 20 30 40 50
Implementation of Postorder Traversal
#include (bits/stdc++.h> using namespace std;
struct Node { int key; struct Node *left; struct Node *right; Node(int k){ key=k; left=right=NULL; } };
void postorder(Node *root){ if(root!=NULL){ postorder(root->left); postorder(root->right); cout((root->key((" "; } }
int main() {
Node *root=new Node(10); root->left=new Node(20); root->right=new Node(30); root->right->left=new Node(40); root->right->right=new Node(50);
postorder(root); } 20 40 50 30 10
Implementation of function to calculate Height of Binary Tree
Height of Binary Tree is the number of nodes between the longest path from root to leaf node(including the root and leaf node).
#include (bits/stdc++.h> using namespace std;
struct Node { int key; struct Node *left; struct Node *right; Node(int k){ key=k; left=right=NULL; } };
int height(Node *root){ if(root==NULL) return 0; else return (1+max(height(root->left),height(root->right))); }
int main() {
Node *root=new Node(10); root->left=new Node(20); root->right=new Node(30); root->right->left=new Node(40); root->right->right=new Node(50);
cout((height(root); } output 3
Print nodes at k distance in a tree
Nodes at distance k from the root are basically the nodes at (k+1)th level of the Binary Tree.
#include (bits/stdc++.h> using namespace std;
struct Node { int key; struct Node *left; struct Node *right; Node(int k){ key=k; left=right=NULL; } };
void printKDist(Node *root,int k){ if(root==NULL)return;
if(k==0){cout((root->key((" ";} else{ printKDist(root->left,k-1); printKDist(root->right,k-1); } }
int main() {
Node *root=new Node(10); root->left=new Node(20); root->right=new Node(30); root->left->left=new Node(40); root->left->right=new Node(50); root->right->right=new Node(70); root->right->right->right=new Node(80); int k=2;
printKDist(root,k); } 40 50 70
Implement level order traversal for a binary tree
Level order traversal of a tree is breadth first traversal of binary tree
#include (bits/stdc++.h> using namespace std;
struct Node { int key; struct Node *left; struct Node *right; Node(int k){ key=k; left=right=NULL; } };
void printLevel(Node *root){ if(root==NULL)return; queue(Node *>q; q.push(root); while(q.empty()==false){ Node *curr=q.front(); q.pop(); cout((curr->key((" "; if(curr->left!=NULL) q.push(curr->left); if(curr->right!=NULL) q.push(curr->right); } }
int main() {
Node *root=new Node(10); root->left=new Node(20); root->right=new Node(30); root->left->left=new Node(40); root->left->right=new Node(50); root->right->left=new Node(60); root->right->right=new Node(70);
printLevel(root); } 10 20 30 40 50 60 70
Calculate size of binary tree
Size of Binary Tree is the total numbers of nodes present in that Tree.
#include (bits/stdc++.h> using namespace std;
struct Node { int key; struct Node *left; struct Node *right; Node(int k){ key=k; left=right=NULL; } };
int getSize(Node *root){ if(root==NULL) return 0; else return 1+getSize(root->left)+getSize(root->right); }
int main() {
Node *root=new Node(10); root->left=new Node(20); root->right=new Node(30); root->left->left=new Node(40); root->left->right=new Node(50); root->right->right=new Node(60);
cout((getSize(root); } 6
Maximum node in a tree
#include (bits/stdc++.h> using namespace std;
struct Node { int key; struct Node *left; struct Node *right; Node(int k){ key=k; left=right=NULL; } };
int getMax(Node *root){ if(root==NULL) return INT_MIN; else return max(root->key,max(getMax(root->left),getMax(root->right))); }
int main() {
Node *root=new Node(20); root->left=new Node(80); root->right=new Node(30); root->right->left=new Node(40); root->right->right=new Node(50);
cout((getMax(root); } 80
Iterative Inorder traversal
TC = theta(n)
SC - O(h)
Iterative Preorder Traversal (Simple)
A O(n) extra space and O(n) time solution
Iterative Preorder Traversal (Space Optimized)
O(h) extra space and O(n) time solution
Children Sum Parent
Given a Binary Tree. Check whether all of its nodes have the value equal to the sum of their child nodes.
Example 1:
Input: 10 / 10 Output: 1 Explanation: Here, every node is sum of its left and right child. Example 2:
Input: 1 / \ 4 3 / \ 5 N Output: 0 Explanation: Here, 1 is the root node and 4, 3 are its child nodes. 4 + 3 = 7 which is not equal to the value of root node. Hence, this tree does not satisfy the given conditions.
Your Task:
You don’t need to read input or print anything. Your task is to complete the function isSumProperty() that takes the root Node of the Binary Tree as input and returns 1 if all the nodes in the tree satisfy the following properties. Else, it returns 0.
For every node, data value must be equal to the sum of data values in left and right children. Consider data value as 0 for NULL child. Also, leaves are considered to follow the property.
Expected Time Complexiy: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Algorithm:
For each node, if node is null or both child nodes are null, return true.
Else if left and right child are not null then store their value.
If sum of stored data of left and right child is equal to the current node data and recursively for the left and right subtree, parent data is equal to sum of child data then return true else return false.
int isSumProperty(struct Node *node) { int left_data = 0, right_data = 0;
//if node is null or both child nodes are null, we return true. if (node == NULL ||(node->left == NULL && node->right == NULL)) return 1;
else {
//if left child is not null then we store its value. if (node->left != NULL) left_data = node->left->data;
//if right child is not null then we store its value. if (node->right != NULL) right_data = node->right->data;
//if sum of stored data of left and right child is equal to the current //node data and recursively for the left and right subtree, parent data //is equal to sum of child data then we return true. if ((node->data == left_data + right_data) && isSumProperty(node->left) && isSumProperty(node->right)) return 1;
//else we return false. else return 0; }
Determine if Two Trees are Identical
Given two binary trees, the task is to find if both of them are identical or not.
Example 2:
Input: 1 1 / \ / \ 2 3 2 3 Output: Yes Explanation: There are two trees both having 3 nodes and 2 edges, both trees are identical having the root as 1, left child of 1 is 2 and right child of 1 is 3. Example 2:
Input: 1 1 / \ / \ 2 3 3 2 Output: No Explanation: There are two trees both having 3 nodes and 2 edges, but both trees are not identical.
Your task:
Since this is a functional problem you don’t have to worry about input, you just have to complete the function isIdentical() that takes two roots as parameters and returns true or false. The printing is done by the driver code.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Two trees are identical when they have same data and arrangement of data is also same. To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees.
Algorithm:
1. If both nodes are empty then return 1.
2. Else If both nodes are non-empty
(a) Check data of the root nodes (tree1->data == tree2->data)
(b) Check left subtrees recursively.
(c) Check right subtrees recursively.
(d) If a,b and c are true then return 1.
3 Else return 0 (one is empty and other is not).
class Solution { public: //Function to check if two trees are identical. bool isIdentical(Node* a, Node* b) { //if both nodes are null then we return true. if (a == NULL && b == NULL) return true;
if (a != NULL && b != NULL) { //we check if data at both nodes and left and right subtree of //both the nodes are equal then we return true else return false. return ( a->data == b->data && isIdentical(a->left, b->left) && isIdentical(a->right, b->right) ); }
//returning false if one of the nodes is null and other isn't. return false; }
};
Level order traversal Line by Line
Given a Binary Tree, your task is to find its level order traversal.
For the below tree the output will be 1 $ 2 3 $ 4 5 6 7 $ 8 $.
1 / \ 2 3 / \ / \ 4 5 6 7 \ 8
Example 1:
Input: 1 / 4 / \ 4 2 Output:1 $ 4 $ 4 2 $
Example 2:
Input: 10 / \ 20 30 / \ 40 60 Output: 10 $ 20 30 $ 40 60 $ Your Task: This is a function problem. You don't need to read input. Just complete the function levelOrder() that takes nodes as parameter and returns level order traversal as a 2D list.
Note: The driver code prints the levels ‘$’ separated.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
This question can be solved by simply using the concept of level order traversal but you just need to keep track of elements in a particular level and add them to final list.
vector(vector(int» levelOrder(struct Node* node)
{
//creating an empty queue for level order traversal.
queue(Node *> q;
q.push(node);
vector(vector(int>> result; while(1) { int size = q.size(); if(size==0) break;
//creating a list to store the nodes at a particular level. vector(int> level;
while(size>0) { //storing front element of queue in list and removing it from queue. Node * node = q.front(); q.pop(); level.push_back(node->data);
//storing the left child of the parent node in queue. if(node->left) q.push(node->left);
//storing the right child of the parent node in queue. if(node->right) q.push(node->right); size--; } //adding the level list in answer. result.push_back(level); } //returning the final list. return result; }
Maximum Width of Tree
Given a Binary Tree, find the maximum width of it. Maximum width is defined as the maximum number of nodes in any level.
For example, maximum width of following tree is 4 as there are 4 nodes at 3rd level.
1 / \ 2 3 / \ / \ 4 5 6 7 \ 8
Example 1:
Input: 1 / \ 2 3 Output: 2 Example 2:
Input: 10 / \ 20 30 / \ 40 60 Output: 2 Your Task: You don't have to read any input. Just complete the function getMaxWidth() that takes node as parameter and returns the maximum width. The printing is done by the driver code.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
(Using Level Order Traversal) This method mainly involves two functions. One is to count nodes at a given level (getWidth), and other is to get the maximum width of the tree(getMaxWidth). getMaxWidth() makes use of getWidth() to get the width of all levels starting from root and compares them to get the maximum. class Solution { public: // Function to get height of a tree. int height(Node* node) { // if node is null, we return 0. if (node == NULL) return 0;
// else we call the function height recursively for left and right // subtrees of the parent node and store their maximum. else { int lHeight = height(node->left); int rHeight = height(node->right); return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } }
public: // Function to get width of a given level. int getWidth(Node* root, int level) {
if (root == NULL) return 0;
// if level is 1, we return 1. if (level == 1) return 1;
// else if it is greater than one, we call the getWidth function // recursively for left and right subtrees of parent node and add them. else if (level > 1) return getWidth(root->left, level - 1) + getWidth(root->right, level - 1); }
public: // Function to get the maximum width of a binary tree. int getMaxWidth(Node* root) { int maxWidth = 0; int width; int h = height(root); int i;
// getting width of each level and comparing the width // with maximum width so far. for (i = 1; i (= h; i++) { width = getWidth(root, i); if (width > maxWidth) maxWidth = width; }
// returning the maximum width. return maxWidth; } };
Given a binary tree, find if it is height balanced or not.
A tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes of tree.
A height balanced tree 1 / \ 10 39 / 5
An unbalanced tree 1 / 10 / 5
Example 1:
Input: 1 / 2 \ 3 Output: 0 Explanation: The max difference in height of left subtree and right subtree is 2, which is greater than 1. Hence unbalanced Example 2:
Input: 10 / \ 20 30 / \ 40 60 Output: 1 Explanation: The max difference in height of left subtree and right subtree is 1. Hence balanced. Your Task: You don't need to take input. Just complete the function isBalanced() that takes root node as parameter and returns true, if the tree is balanced else returns false.
Constraints:
1 <= Number of nodes <= 105
0 <= Data of a node <= 106
Expected time complexity: O(N)
Expected auxiliary space: O(h) , where h = height of tree
O(N) solution
int height(Node*root){ if(root==NULL)return 0; return 1+max(height(root→left),height(root→right)); } bool isBalanced(Node *root) { // Your Code here bool flag=true; if(root==NULL) return flag; queue(Node*> q; q.push(root); while(!q.empty()){ Node*node=q.front(); q.pop(); if(abs(height(node->left)-height(node->right))>1) { flag=false; break; } if(node->left!=NULL)q.push(node->left); if(node->right!=NULL)q.push(node->right); } return flag; }
Left View of Binary Tree
Given a Binary Tree, print Left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from Left side. The task is to complete the function leftView(), which accepts root of the tree as argument.
Left view of following tree is 1 2 4 8.
1 / \ 2 3 / \ / \ 4 5 6 7 \ 8
Example 1:
Input: 1 / \ 3 2 Output: 1 3
Example 2:
Input:
Output: 10 20 40
Your Task:
You just have to complete the function leftView() that prints the left view. The newline is automatically appended by the driver code.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Method-2 (Using Queue):
In this method, level order traversal based solution is discussed. If we observe carefully, we will see that our main task is to print the left most node of every level. So, we will do a level order traversal on the tree and print the leftmost node at every level. Below is the implementation of above approach:
// C++ program to print left view of // Binary Tree
#include(bits/stdc++.h> using namespace std;
// A Binary Tree Node struct Node { int data; struct Node *left, *right; };
// Utility function to create a new tree node Node* newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; }
// function to print left view of // binary tree void printLeftView(Node* root) { if (!root) return;
queue(Node*> q; q.push(root);
while (!q.empty()) { // number of nodes at current level int n = q.size();
// Traverse all nodes of current level for(int i = 1; i (= n; i++) { Node* temp = q.front(); q.pop();
// Print the left most element // at the level if (i == 1) cout((temp->data((" "; // Add left node to queue if (temp->left != NULL) q.push(temp->left);
// Add right node to queue if (temp->right != NULL) q.push(temp->right); } } }
// Driver code int main() { // Let's construct the tree as // shown in example
Node* root = newNode(10); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(8); root->right->right = newNode(15); root->right->left = newNode(12); root->right->right->left = newNode(14);
printLeftView(root); }
// This code is contributed by // Manne SreeCharan
Right View of Binary Tree
Given a Binary Tree, find Right view of it. Right view of a Binary Tree is set of nodes visible when tree is viewed from right side.
Right view of following tree is 1 3 7 8.
1 / \ 2 3 / \ / \ 4 5 6 7 \ 8
Example 1:
Input: 1 / \ 3 2 Output: 1 2 Example 2:
Input: 10 / \ 20 30 / \ 40 60 Output: 10 30 60 Your Task: Just complete the function rightView() that takes node as parameter and returns the right view as a list.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
The problem can be solved using simple recursive traversal. We can keep track of level of a node by passing a parameter to all recursive calls. The idea is to keep track of maximum level also. And traverse the tree in a manner that right subtree is visited before left subtree. Whenever we see a node whose level is more than maximum level so far, we print the node because this is the last node in its level (Note that we traverse the right subtree before left subtree). Following is the implementation of this approach. class Solution { public: //Function to get the right view of the binary tree. void rightViewUtil(vector(int> &vec,struct Node *root,int level,int *max_level) { //if root is null, we simply return. if (root==NULL) return;
//if this is the last node of its level then it is in the right view. if (*max_level ( level) { vec.push_back(root->data); *max_level = level; }
//calling function recursively for right and left //subtrees of current node. rightViewUtil(vec, root->right, level+1, max_level); rightViewUtil(vec, root->left, level+1, max_level); }
public: //Function to return list containing elements of right view of binary tree. vector(int> rightView(struct Node *root) { int max_level = 0; vector(int> vec; rightViewUtil(vec,root, 1, &max_level); //returning the list. return vec; } }; Time Complexity: The function does a simple traversal of the tree, so the complexity is O(n).
Method 2: In this method, level order traversal based solution is discussed. If we observe carefully, we will see that our main task is to print the right most node of every level. So, we will do a level order traversal on the tree and print the last node at every level. Below is the implementation of above approach:
vector(int> rightView(Node *root) { vector(int>v; queue(Node*>q; q.push(root); while(!q.empty()){ int n=q.size(); for(int i=0;i(n;i++){ Node *temp=q.front(); q.pop(); if(i==n-1){ v.push_back(temp->data); } if(temp->left!=NULL){ q.push(temp->left); } if(temp->right!=NULL){ q.push(temp->right); }
} } return v; }
Lowest Common Ancestor in a Binary Tree
Given a Binary Tree with all unique values and two nodes value, n1 and n2. The task is to find the lowest common ancestor of the given two nodes. We may assume that either both n1 and n2 are present in the tree or none of them are present.
Example 1:
Input: n1 = 2 , n2 = 3 1 / \ 2 3 Output: 1 Explanation: LCA of 2 and 3 is 1. Example 2:
Input: n1 = 3 , n2 = 4 5 / 2 / \ 3 4 Output: 2 Explanation: LCA of 3 and 4 is 2. Your Task: You don't have to read, input, or print anything. Your task is to complete the function lca() that takes nodes, n1, and n2 as parameters and returns the LCA node as output. Otherwise, return a node with a value of -1 if both n1 and n2 are not present in the tree.
Expected Time Complexity:O(N).
Expected Auxiliary Space:O(Height of Tree).
Following is definition of LCA from Wikipedia: Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself). The LCA of n1 and n2 in T is the shared ancestor of n1 and n2 that is located farthest from the root. Computation of lowest common ancestors may be useful, for instance, as part of a procedure for determining the distance between pairs of nodes in a tree: the distance from n1 to n2 can be computed as the distance from the root to n1, plus the distance from the root to n2, minus twice the distance from the root to their lowest common ancestor. Method 1 (By Storing root to n1 and root to n2 paths):
Following is simple O(n) algorithm to find lowest common ancestor of two numbers n1 and n2.
Find path from root to n1 and store it in a vector or array.
Find path from root to n2 and store it in another vector or array.
Traverse both paths till the values in arrays are same. Return the common element just before the mismatch.
Try another efficient approach using parent array.
bool findPath(Node *root, vector(int> &path, int k) { // base case if (root == NULL) return false;
// Store this node in path vector. The node will be removed if // not in path from root to k path.push_back(root->key);
// See if the k is same as root's key if (root->key == k) return true;
// Check if k is found in left or right sub-tree if ( (root->left && findPath(root->left, path, k)) || (root->right && findPath(root->right, path, k)) ) return true;
// If not present in subtree rooted with root, remove root from // path[] and return false path.pop_back(); return false; }
// Returns LCA if node n1, n2 are present in the given binary tree, // otherwise return -1 int findLCA(Node *root, int n1, int n2) { // to store paths to n1 and n2 from the root vector(int> path1, path2;
// Find paths from root to n1 and root to n1. If either n1 or n2 // is not present, return -1 if ( !findPath(root, path1, n1) || !findPath(root, path2, n2)) return -1;
/* Compare the paths to get the first different value */ int i; for (i = 0; i ( path1.size() && i ( path2.size() ; i++) if (path1[i] != path2[i]) break; return path1[i-1]; }
Method 2
The question is simply asking to find the subtree’s root which will contain both n1 and n2, right?! So we do the same,
Well, if there is no root, you gotta return null/root. if(root==nullptr) { return root; }
if your root data contains either n1 or n2, you return that root. WHY?? because it will be used in calculation of two different answer A.K.A. left and right side of tree.
Now save your Left answer of the left side of tree in a variable, this variable with either have a null or a valid node depending on recursive calls if it finds the required node, Do the same for the Right side make a variable and save the answer.
Now, we have two different variables namely left and right. Both contains answer either null or a valid node, now we check three conditions
If Left answer is not null and right answer is also not null, then the answer is the root itself, since left and right are subtrees of the root and if both are not null it clearly means the values n1 and n2 lies in right as well as left side, For example, Example test case 1 is the perfect example for this case
If left answer is not null but right answer is null, then it means both n1 and n2 lies on the left side of tree inside the subtree with root as left answer, return left answer. For example, Example test case 2 is the perfect example for this case
If right answer is not null but left answer is null, then it means both n1 and n2 lies on the right side of tree inside the subtree with root as right answer, return right answer.
Node* lca(Node* root ,int n1 ,int n2 )
{
if (root == NULL) return root;
if (root->data == n1 or root->data == n2) return root;
Node* left = lca(root->left, n1, n2); Node* right = lca(root->right, n1, n2);
if(left != NULL and right != NULL) return root; else if (left != NULL) return left; else return right; }
Diameter of a Binary Tree
The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes. The diagram below shows two trees each with diameter nine, the leaves that form the ends of the longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes).
Example 1:
Input: 1 / \ 2 3 Output: 3 Example 2:
Input: 10 / \ 20 30 / \ 40 60 Output: 4 Your Task: You need to complete the function diameter() that takes root as parameter and returns the diameter.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
The diameter of a tree T is the largest of the following quantities:
The diameter of T’s left subtree.
The diameter of T’s right subtree.
The longest path between leaves that goes through the root of T (this can be computed from the heights of the subtrees of T).
int ht(Node* root) { if(!root) return 0; if(!root->left and !root->right) return 1; int ld = 1 + ht(root->left); int rd = 1 + ht(root->right);
return max(ld, rd); } int diameter(Node* root) { int res = 0; queue q; q.push(root); while(!q.empty()) { Node* temp = q.front(); res = max(res, 1 + ht(temp->left) + ht(temp->right)); q.pop(); if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); } return res; }
Optimized implementation: The above implementation can be optimized by calculating the height in the same recursion rather than calling a height() separately. Thanks to Amar for suggesting this optimized version. This optimization reduces time complexity to O(n).
// Recursive optimized C++ program to find the diameter of a // Binary Tree #include (bits/stdc++.h> using namespace std;
// A binary tree node has data, pointer to left child // and a pointer to right child struct node { int data; struct node *left, *right; };
// function to create a new node of tree and returns pointer struct node* newNode(int data);
int diameterOpt(struct node* root, int* height) { // lh --> Height of left subtree // rh --> Height of right subtree int lh = 0, rh = 0;
// ldiameter --> diameter of left subtree // rdiameter --> Diameter of right subtree int ldiameter = 0, rdiameter = 0;
if (root == NULL) { *height = 0; return 0; // diameter is also 0 }
// Get the heights of left and right subtrees in lh and // rh And store the returned values in ldiameter and // ldiameter ldiameter = diameterOpt(root->left, &lh); rdiameter = diameterOpt(root->right, &rh);
// Height of current node is max of heights of left and // right subtrees plus 1 *height = max(lh, rh) + 1;
return max(lh + rh + 1, max(ldiameter, rdiameter)); }
// Helper function that allocates a new node with the // given data and NULL left and right pointers. struct node* newNode(int data) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL;
return (node); }
// Driver Code int main() {
/* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5);
int height = 0; // Function Call cout (( "Diameter of the given binary tree is " (( diameterOpt(root, &height);
return 0; }
// This code is contributed by probinsah.
Vertical Width of a Binary Tree
Given a Binary Tree of N nodes. Find the vertical width of the tree.
Example 1:
Input: 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 Output: 6 Explanation: The width of a binary tree is the number of vertical paths in that tree.
Example 2:
Input: 1 / \ 2 3 Output: 3
Your Task:
You don’t have to read input or print anything. Your task is to complete the function verticalWidth() which takes root as the only parameter, and returns the vertical width of the binary tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Maintain 3 variables maximum and minimum, and curr.
Maximum and Minimum will store the max value of width of tree and min value of width of tree, over all recursion calls.
- Pass Maximum and Minimum through reference for updation.
- For call on left subree pass curr-1 and for call on right subree pass curr + 1
After all the calls have been made, return the sum of maximum and absolute value of minimum+1.
void lengthUtil(Node* root, int &maximum, int &minimum, int curr) { //base case for recursion. if (root == NULL)return;
//calling the lengthUtil function recursively for the left subtrees. lengthUtil(root->left, maximum, minimum, curr - 1);
//updating maximum and minimum. if (minimum > curr)minimum = curr; if (maximum ( curr)maximum = curr;
//calling the lengthUtil function recursively for the right subtrees. lengthUtil(root->right, maximum, minimum, curr + 1); }
//Function to find the vertical width of a Binary Tree. int verticalWidth(Node* root) { if (!root) { return 0; } int maximum = 0, minimum = 0; lengthUtil(root, maximum, minimum, 0); //returning the result. return (abs(minimum) + maximum) + 1; }
Mirror Tree
Your Task:
Just complete the function mirror() that takes node as paramter and convert it into its mirror. The printing is done by the driver code only.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
// Function to convert a binary tree into its mirror tree. void mirror(Node* node) { if (!node) return; swap(node->left, node->right); mirror(node->left); mirror(node->right); }