code
stringlengths 195
7.9k
| space_complexity
stringclasses 6
values | time_complexity
stringclasses 7
values |
---|---|---|
// C++ Program to convert a Binary Tree
// to a Circular Doubly Linked List
#include <iostream>
using namespace std;
// To represents a node of a Binary Tree
struct Node {
struct Node *left, *right;
int data;
};
// A function that appends rightList at the end
// of leftList.
Node* concatenate(Node* leftList, Node* rightList)
{
// If either of the list is empty
// then return the other list
if (leftList == NULL)
return rightList;
if (rightList == NULL)
return leftList;
// Store the last Node of left List
Node* leftLast = leftList->left;
// Store the last Node of right List
Node* rightLast = rightList->left;
// Connect the last node of Left List
// with the first Node of the right List
leftLast->right = rightList;
rightList->left = leftLast;
// Left of first node points to
// the last node in the list
leftList->left = rightLast;
// Right of last node refers to the first
// node of the List
rightLast->right = leftList;
return leftList;
}
// Function converts a tree to a circular Linked List
// and then returns the head of the Linked List
Node* bTreeToCList(Node* root)
{
if (root == NULL)
return NULL;
// Recursively convert left and right subtrees
Node* left = bTreeToCList(root->left);
Node* right = bTreeToCList(root->right);
// Make a circular linked list of single node
// (or root). To do so, make the right and
// left pointers of this node point to itself
root->left = root->right = root;
// Step 1 (concatenate the left list with the list
// with single node, i.e., current node)
// Step 2 (concatenate the returned list with the
// right List)
return concatenate(concatenate(left, root), right);
}
// Display Circular Link List
void displayCList(Node* head)
{
cout << "Circular Linked List is :\n";
Node* itr = head;
do {
cout << itr->data << " ";
itr = itr->right;
} while (head != itr);
cout << "\n";
}
// Create a new Node and return its address
Node* newNode(int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver Program to test above function
int main()
{
Node* root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
Node* head = bTreeToCList(root);
displayCList(head);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129) | logn | linear |
// A C++ program for in-place conversion of Binary Tree to
// CDLL
#include <iostream>
using namespace std;
/* A binary tree node has - data , left and right pointers
*/
struct Node {
int data;
Node* left;
Node* right;
};
// A utility function that converts given binary tree to
// a doubly linked list
// root --> the root of the binary tree
// head --> head of the created doubly linked list
Node* BTree2DoublyLinkedList(Node* root, Node** head)
{
// Base case
if (root == NULL)
return root;
// Initialize previously visited node as NULL. This is
// static so that the same value is accessible in all
// recursive calls
static Node* prev = NULL;
// Recursively convert left subtree
BTree2DoublyLinkedList(root->left, head);
// Now convert this node
if (prev == NULL)
*head = root;
else {
root->left = prev;
prev->right = root;
}
prev = root;
// Finally convert right subtree
BTree2DoublyLinkedList(root->right, head);
return prev;
}
// A simple recursive function to convert a given Binary
// tree to Circular Doubly Linked List using a utility
// function root --> Root of Binary Tree tail --> Pointer to
// tail node of created circular doubly linked list
Node* BTree2CircularDoublyLinkedList(Node* root)
{
Node* head = NULL;
Node* tail = BTree2DoublyLinkedList(root, &head);
// make the changes to convert a DLL to CDLL
tail->right = head;
head->left = tail;
// return the head of the created CDLL
return head;
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
Node* newNode(int data)
{
Node* new_node = new Node;
new_node->data = data;
new_node->left = new_node->right = NULL;
return (new_node);
}
/* Function to print nodes in a given circular doubly linked
* list */
void printList(Node* head)
{
if (head == NULL)
return;
Node* ptr = head;
do {
cout << ptr->data << " ";
ptr = ptr->right;
} while (ptr != head);
}
/* Driver program to test above functions*/
int main()
{
// Let us create the tree shown in above diagram
Node* root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
// Convert to DLL
Node* head = BTree2CircularDoublyLinkedList(root);
// Print the converted list
printList(head);
return 0;
}
// This code was contributed by Abhijeet
// Kumar(abhijeet19403) | logn | linear |
// C++ program to convert a ternary expression to
// a tree.
#include<bits/stdc++.h>
using namespace std;
// tree structure
struct Node
{
char data;
Node *left, *right;
};
// function create a new node
Node *newNode(char Data)
{
Node *new_node = new Node;
new_node->data = Data;
new_node->left = new_node->right = NULL;
return new_node;
}
// Function to convert Ternary Expression to a Binary
// Tree. It return the root of tree
// Notice that we pass index i by reference because we
// want to skip the characters in the subtree
Node *convertExpression(string str, int & i)
{
// store current character of expression_string
// [ 'a' to 'z']
Node * root =newNode(str[i]);
//If it was last character return
//Base Case
if(i==str.length()-1) return root;
// Move ahead in str
i++;
//If the next character is '?'.Then there will be subtree for the current node
if(str[i]=='?')
{
//skip the '?'
i++;
// construct the left subtree
// Notice after the below recursive call i will point to ':'
// just before the right child of current node since we pass i by reference
root->left = convertExpression(str,i);
//skip the ':' character
i++;
//construct the right subtree
root->right = convertExpression(str,i);
return root;
}
//If the next character is not '?' no subtree just return it
else return root;
}
// function print tree
void printTree( Node *root)
{
if (!root)
return ;
cout << root->data <<" ";
printTree(root->left);
printTree(root->right);
}
// Driver program to test above function
int main()
{
string expression = "a?b?c:d:e";
int i=0;
Node *root = convertExpression(expression, i);
printTree(root) ;
return 0;
} | linear | linear |
// C++ program for Minimum swap required
// to convert binary tree to binary search tree
#include<bits/stdc++.h>
using namespace std;
// Inorder Traversal of Binary Tree
void inorder(int a[], std::vector<int> &v,
int n, int index)
{
// if index is greater or equal to vector size
if(index >= n)
return;
inorder(a, v, n, 2 * index + 1);
// push elements in vector
v.push_back(a[index]);
inorder(a, v, n, 2 * index + 2);
}
// Function to find minimum swaps to sort an array
int minSwaps(std::vector<int> &v)
{
std::vector<pair<int,int> > t(v.size());
int ans = 0;
for(int i = 0; i < v.size(); i++)
t[i].first = v[i], t[i].second = i;
sort(t.begin(), t.end());
for(int i = 0; i < t.size(); i++)
{
// second element is equal to i
if(i == t[i].second)
continue;
else
{
// swapping of elements
swap(t[i].first, t[t[i].second].first);
swap(t[i].second, t[t[i].second].second);
}
// Second is not equal to i
if(i != t[i].second)
--i;
ans++;
}
return ans;
}
// Driver code
int main()
{
int a[] = { 5, 6, 7, 8, 9, 10, 11 };
int n = sizeof(a) / sizeof(a[0]);
std::vector<int> v;
inorder(a, v, n, 0);
cout << minSwaps(v) << endl;
}
// This code is contributed by code_freak | linear | nlogn |
/* Program to check children sum property */
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, left
child and right child */
struct node {
int data;
struct node* left;
struct node* right;
};
/* returns 1 if children sum property holds
for the given node and both of its children*/
int isSumProperty(struct node* node)
{
/* left_data is left child data and
right_data is for right child data*/
int sum = 0;
/* If node is NULL or it's a leaf node
then return true */
if (node == NULL
|| (node->left == NULL && node->right == NULL))
return 1;
else {
/* If left child is not present then 0
is used as data of left child */
if (node->left != NULL)
sum += node->left->data;
/* If right child is not present then 0
is used as data of right child */
if (node->right != NULL)
sum += node->right->data;
/* if the node and both of its children
satisfy the property return 1 else 0*/
return ((node->data == sum)
&& isSumProperty(node->left)
&& isSumProperty(node->right));
}
}
/*
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()
{
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->right = newNode(2);
// Function call
if (isSumProperty(root))
cout << "The given tree satisfies "
<< "the children sum property ";
else
cout << "The given tree does not satisfy "
<< "the children sum property ";
getchar();
return 0;
}
// This code is contributed by Akanksha Rai | logn | linear |
// C++ program to check if two Nodes in a binary tree are
// cousins
#include <bits/stdc++.h>
using namespace std;
// A Binary Tree Node
struct Node {
int data;
struct Node *left, *right;
};
// A utility function to create a new Binary Tree Node
struct Node* newNode(int item)
{
struct Node* temp
= new Node;
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
// Recursive function to check if two Nodes are siblings
int isSibling(struct Node* root, struct Node* a,
struct Node* b)
{
// Base case
if (root == NULL)
return 0;
return ((root->left == a && root->right == b)
|| (root->left == b && root->right == a)
|| isSibling(root->left, a, b)
|| isSibling(root->right, a, b));
}
// Recursive function to find level of Node 'ptr' in a
// binary tree
int level(struct Node* root, struct Node* ptr, int lev)
{
// base cases
if (root == NULL)
return 0;
if (root == ptr)
return lev;
// Return level if Node is present in left subtree
int l = level(root->left, ptr, lev + 1);
if (l != 0)
return l;
// Else search in right subtree
return level(root->right, ptr, lev + 1);
}
// Returns 1 if a and b are cousins, otherwise 0
int isCousin(struct Node* root, struct Node* a, struct Node* b)
{
// 1. The two Nodes should be on the same level in the
// binary tree.
// 2. The two Nodes should not be siblings (means that
// they should
// not have the same parent Node).
if ((level(root, a, 1) == level(root, b, 1)) && !(isSibling(root, a, b)))
return 1;
else
return 0;
}
// Driver Program to test above functions
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->right->right = newNode(15);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
struct Node *Node1, *Node2;
Node1 = root->left->left;
Node2 = root->right->right;
if (isCousin(root, Node1, Node2))
printf("Yes\n");
else
printf("No\n");
return 0;
}
// This code is contributed by ajaymakwana | linear | linear |
// C++ program to check if all leaves
// are at same level
#include <bits/stdc++.h>
using namespace std;
// A binary tree node
struct Node
{
int data;
struct Node *left, *right;
};
// A utility function to allocate
// a new tree node
struct Node* newNode(int data)
{
struct Node* node = (struct Node*) malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
/* Recursive function which checks whether
all leaves are at same level */
bool checkUtil(struct Node *root,
int level, int *leafLevel)
{
// Base case
if (root == NULL) return true;
// If a leaf node is encountered
if (root->left == NULL &&
root->right == NULL)
{
// When a leaf node is found
// first time
if (*leafLevel == 0)
{
*leafLevel = level; // Set first found leaf's level
return true;
}
// If this is not first leaf node, compare
// its level with first leaf's level
return (level == *leafLevel);
}
// If this node is not leaf, recursively
// check left and right subtrees
return checkUtil(root->left, level + 1, leafLevel) &&
checkUtil(root->right, level + 1, leafLevel);
}
/* The main function to check
if all leafs are at same level.
It mainly uses checkUtil() */
bool check(struct Node *root)
{
int level = 0, leafLevel = 0;
return checkUtil(root, level, &leafLevel);
}
// Driver Code
int main()
{
// Let us create tree shown in third example
struct Node *root = newNode(12);
root->left = newNode(5);
root->left->left = newNode(3);
root->left->right = newNode(9);
root->left->left->left = newNode(1);
root->left->right->left = newNode(1);
if (check(root))
cout << "Leaves are at same level\n";
else
cout << "Leaves are not at same level\n";
getchar();
return 0;
}
// This code is contributed
// by Akanksha Rai | linear | linear |
// C++ program to check if all leaf nodes are at
// same level of binary tree
#include <bits/stdc++.h>
using namespace std;
// tree node
struct Node {
int data;
Node *left, *right;
};
// returns a new tree Node
Node* newNode(int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// return true if all leaf nodes are
// at same level, else false
int checkLevelLeafNode(Node* root)
{
if (!root)
return 1;
// create a queue for level order traversal
queue<Node*> q;
q.push(root);
int result = INT_MAX;
int level = 0;
// traverse until the queue is empty
while (!q.empty()) {
int size = q.size();
level += 1;
// traverse for complete level
while(size > 0){
Node* temp = q.front();
q.pop();
// check for left child
if (temp->left) {
q.push(temp->left);
// if its leaf node
if(!temp->left->right && !temp->left->left){
// if it's first leaf node, then update result
if (result == INT_MAX)
result = level;
// if it's not first leaf node, then compare
// the level with level of previous leaf node
else if (result != level)
return 0;
}
}
// check for right child
if (temp->right){
q.push(temp->right);
// if it's leaf node
if (!temp->right->left && !temp->right->right)
// if it's first leaf node till now,
// then update the result
if (result == INT_MAX)
result = level;
// if it is not the first leaf node,
// then compare the level with level
// of previous leaf node
else if(result != level)
return 0;
}
size -= 1;
}
}
return 1;
}
// driver program
int main()
{
// construct a tree
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
int result = checkLevelLeafNode(root);
if (result)
cout << "All leaf nodes are at same level\n";
else
cout << "Leaf nodes not at same level\n";
return 0;
} | linear | linear |
// C++ program to check if there exist an edge whose
// removal creates two trees of same size
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* left, *right;
};
// utility function to create a new node
struct Node* newNode(int x)
{
struct Node* temp = new Node;
temp->data = x;
temp->left = temp->right = NULL;
return temp;
};
// To calculate size of tree with given root
int count(Node* root)
{
if (root==NULL)
return 0;
return count(root->left) + count(root->right) + 1;
}
// This function returns true if there is an edge
// whose removal can divide the tree in two halves
// n is size of tree
bool checkRec(Node* root, int n)
{
// Base cases
if (root ==NULL)
return false;
// Check for root
if (count(root) == n-count(root))
return true;
// Check for rest of the nodes
return checkRec(root->left, n) ||
checkRec(root->right, n);
}
// This function mainly uses checkRec()
bool check(Node *root)
{
// Count total nodes in given tree
int n = count(root);
// Now recursively check all nodes
return checkRec(root, n);
}
// Driver code
int main()
{
struct Node* root = newNode(5);
root->left = newNode(1);
root->right = newNode(6);
root->left->left = newNode(3);
root->right->left = newNode(7);
root->right->right = newNode(4);
check(root)? printf("YES") : printf("NO");
return 0;
} | linear | quadratic |
// C++ program to check if there exist an edge whose
// removal creates two trees of same size
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* left, *right;
};
// utility function to create a new node
struct Node* newNode(int x)
{
struct Node* temp = new Node;
temp->data = x;
temp->left = temp->right = NULL;
return temp;
};
// To calculate size of tree with given root
int count(Node* root)
{
if (root==NULL)
return 0;
return count(root->left) + count(root->right) + 1;
}
// This function returns size of tree rooted with given
// root. It also set "res" as true if there is an edge
// whose removal divides tree in two halves.
// n is size of tree
int checkRec(Node* root, int n, bool &res)
{
// Base case
if (root == NULL)
return 0;
// Compute sizes of left and right children
int c = checkRec(root->left, n, res) + 1 +
checkRec(root->right, n, res);
// If required property is true for current node
// set "res" as true
if (c == n-c)
res = true;
// Return size
return c;
}
// This function mainly uses checkRec()
bool check(Node *root)
{
// Count total nodes in given tree
int n = count(root);
// Initialize result and recursively check all nodes
bool res = false;
checkRec(root, n, res);
return res;
}
// Driver code
int main()
{
struct Node* root = newNode(5);
root->left = newNode(1);
root->right = newNode(6);
root->left->left = newNode(3);
root->right->left = newNode(7);
root->right->right = newNode(4);
check(root)? printf("YES") : printf("NO");
return 0;
} | linear | linear |
/* C++ program to check if all three given
traversals are of the same 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 find index of value in arr[start...end]
The function assumes that value is present in in[] */
int search(int arr[], int strt, int end, int value)
{
for (int i = strt; i <= end; i++)
{
if(arr[i] == value)
return i;
}
}
/* Recursive function to construct binary tree
of size len from Inorder traversal in[] and
Preorder traversal pre[]. Initial values
of inStrt and inEnd should be 0 and len -1.
The function doesn't do any error checking for
cases where inorder and preorder do not form a
tree */
Node* buildTree(int in[], int pre[], int inStrt,
int inEnd)
{
static int preIndex = 0;
if(inStrt > inEnd)
return NULL;
/* Pick current node from Preorder traversal
using preIndex and increment preIndex */
Node *tNode = newNode(pre[preIndex++]);
/* If this node has no children then return */
if (inStrt == inEnd)
return tNode;
/* Else find the index of this node in
Inorder traversal */
int inIndex = search(in, inStrt, inEnd, tNode->data);
/* Using index in Inorder traversal,
construct left and right subtress */
tNode->left = buildTree(in, pre, inStrt, inIndex-1);
tNode->right = buildTree(in, pre, inIndex+1, inEnd);
return tNode;
}
/* function to compare Postorder traversal
on constructed tree and given Postorder */
int checkPostorder(Node* node, int postOrder[], int index)
{
if (node == NULL)
return index;
/* first recur on left child */
index = checkPostorder(node->left,postOrder,index);
/* now recur on right child */
index = checkPostorder(node->right,postOrder,index);
/* Compare if data at current index in
both Postorder traversals are same */
if (node->data == postOrder[index])
index++;
else
return -1;
return index;
}
// Driver program to test above functions
int main()
{
int inOrder[] = {4, 2, 5, 1, 3};
int preOrder[] = {1, 2, 4, 5, 3};
int postOrder[] = {4, 5, 2, 3, 1};
int len = sizeof(inOrder)/sizeof(inOrder[0]);
// build tree from given
// Inorder and Preorder traversals
Node *root = buildTree(inOrder, preOrder, 0, len - 1);
// compare postorder traversal on constructed
// tree with given Postorder traversal
int index = checkPostorder(root,postOrder,0);
// If both postorder traversals are same
if (index == len)
cout << "Yes";
else
cout << "No";
return 0;
} | linear | quadratic |
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
Node(int val)
{
data = val;
left = right = NULL;
}
};
Node* buildTreeFromInorderPreorder(
int inStart, int inEnd, int& preIndex, int preorder[],
unordered_map<int, int>& inorderIndexMap,
bool& notPossible)
{
if (inStart > inEnd)
return NULL;
// build the current Node
int rootData = preorder[preIndex];
Node* root = new Node(rootData);
preIndex++;
// find the node in inorderIndexMap
if (inorderIndexMap.find(rootData)
== inorderIndexMap.end()) {
notPossible = true;
return root;
}
int inorderIndex = inorderIndexMap[rootData];
if (!(inStart <= inorderIndex
&& inorderIndex <= inEnd)) {
notPossible = true;
return root;
}
int leftInorderStart = inStart,
leftInorderEnd = inorderIndex - 1,
rightInorderStart = inorderIndex + 1,
rightInorderEnd = inEnd;
root->left = buildTreeFromInorderPreorder(
leftInorderStart, leftInorderEnd, preIndex,
preorder, inorderIndexMap, notPossible);
if (notPossible)
return root;
root->right = buildTreeFromInorderPreorder(
rightInorderStart, rightInorderEnd, preIndex,
preorder, inorderIndexMap, notPossible);
return root;
}
bool checkPostorderCorrect(Node* root, int& postIndex,
int postorder[])
{
if (!root)
return true;
if (!checkPostorderCorrect(root->left, postIndex,
postorder))
return false;
if (!checkPostorderCorrect(root->right, postIndex,
postorder))
return false;
return (root->data == postorder[postIndex++]);
}
void printPostorder(Node* root)
{
if (!root)
return;
printPostorder(root->left);
printPostorder(root->right);
cout << root->data << ", ";
}
void printInorder(Node* root)
{
if (!root)
return;
printInorder(root->left);
cout << root->data << ", ";
printInorder(root->right);
}
bool checktree(int preorder[], int inorder[],
int postorder[], int N)
{
// Your code goes here
if (N == 0)
return true;
unordered_map<int, int> inorderIndexMap;
for (int i = 0; i < N; i++)
inorderIndexMap[inorder[i]] = i;
int preIndex = 0;
// return checkInorderPreorder(0, N - 1, preIndex,
// preorder, inorderIndexMap) &&
// checkInorderPostorder(0, N - 1, postIndex, postorder,
// inorderIndexMap);
bool notPossible = false;
Node* root = buildTreeFromInorderPreorder(
0, N - 1, preIndex, preorder, inorderIndexMap,
notPossible);
if (notPossible)
return false;
int postIndex = 0;
return checkPostorderCorrect(root, postIndex,
postorder);
}
// Driver program to test above functions
int main()
{
int inOrder[] = { 4, 2, 5, 1, 3 };
int preOrder[] = { 1, 2, 4, 5, 3 };
int postOrder[] = { 4, 5, 2, 3, 1 };
int len = sizeof(inOrder) / sizeof(inOrder[0]);
// If both postorder traversals are same
if (checktree(preOrder, inOrder, postOrder, len))
cout << "Yes";
else
cout << "No";
return 0;
} | linear | linear |
// C++ code to check if leaf traversals
// of two Binary Trees are same or not.
#include <bits/stdc++.h>
using namespace std;
// Binary Tree Node
struct Node {
int data;
Node* left;
Node* right;
};
// Returns new Node with data as
// input to below function.
Node* newNode(int d)
{
Node* temp = new Node;
temp->data = d;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// checks if a given node is leaf or not.
bool isLeaf(Node* root)
{
if (root == NULL)
return false;
if (!root->left && !root->right)
return true;
return false;
}
// iterative function.
// returns true if leaf traversals
// are same, else false.
bool isSame(Node* root1, Node* root2)
{
stack<Node*> s1;
stack<Node*> s2;
// push root1 to empty stack s1.
s1.push(root1);
// push root2 to empty stack s2.
s2.push(root2);
// loop until either of stacks are non-empty.
while (!s1.empty() || !s2.empty())
{
// this means one of the stacks has
// extra leaves, hence return false.
if (s1.empty() || s2.empty())
return false;
Node* temp1 = s1.top();
s1.pop();
while (temp1 != NULL && !isLeaf(temp1))
{
// Push right child if exists
if (temp1->right)
s1.push(temp1->right);
// Push left child if exists
if (temp1->left)
s1.push(temp1->left);
// Note that right child(if exists)
// is pushed before left child(if exists).
temp1 = s1.top();
s1.pop();
}
Node* temp2 = s2.top();
s2.pop();
while (temp2 != NULL && !isLeaf(temp2))
{
// Push right child if exists
if (temp2->right)
s2.push(temp2->right);
// Push left child if exists
if (temp2->left)
s2.push(temp2->left);
temp2 = s2.top();
s2.pop();
}
if (!temp1 && temp2 || temp1 && !temp2)
return false;
if (temp1 && temp2 && temp1->data!=temp2->data) {
return false;
}
}
// all leaves are matched
return true;
}
// Driver Code
int main()
{
Node* root1 = newNode(1);
root1->left = newNode(2);
root1->right = newNode(3);
root1->left->left = newNode(4);
root1->right->left = newNode(6);
root1->right->right = newNode(7);
Node* root2 = newNode(0);
root2->left = newNode(1);
root2->right = newNode(5);
root2->left->right = newNode(4);
root2->right->left = newNode(6);
root2->right->right = newNode(7);
if (isSame(root1, root2))
cout << "Same";
else
cout << "Not Same";
return 0;
}
// This code is contributed
// by AASTHA VARMA | nlogn | linear |
// C++ program to check whether a given Binary Tree is full or not
#include <bits/stdc++.h>
using namespace std;
/* Tree node structure */
struct Node
{
int key;
struct Node *left, *right;
};
/* Helper function that allocates a new node with the
given key and NULL left and right pointer. */
struct Node *newNode(char k)
{
struct Node *node = new Node;
node->key = k;
node->right = node->left = NULL;
return node;
}
/* This function tests if a binary tree is a full binary tree. */
bool isFullTree (struct Node* root)
{
// If empty tree
if (root == NULL)
return true;
// If leaf node
if (root->left == NULL && root->right == NULL)
return true;
// If both left and right are not NULL, and left & right subtrees
// are full
if ((root->left) && (root->right))
return (isFullTree(root->left) && isFullTree(root->right));
// We reach here when none of the above if conditions work
return false;
}
// Driver Program
int main()
{
struct Node* root = NULL;
root = newNode(10);
root->left = newNode(20);
root->right = newNode(30);
root->left->right = newNode(40);
root->left->left = newNode(50);
root->right->left = newNode(60);
root->right->right = newNode(70);
root->left->left->left = newNode(80);
root->left->left->right = newNode(90);
root->left->right->left = newNode(80);
root->left->right->right = newNode(90);
root->right->left->left = newNode(80);
root->right->left->right = newNode(90);
root->right->right->left = newNode(80);
root->right->right->right = newNode(90);
if (isFullTree(root))
cout << "The Binary Tree is full\n";
else
cout << "The Binary Tree is not full\n";
return(0);
}
// This code is contributed by shubhamsingh10 | linear | linear |
// c++ program to check whether a given BT is full or not
#include <bits/stdc++.h>
using namespace std;
// Tree node structure
struct Node {
int val;
Node *left, *right;
};
// fun that creates and returns a new node
Node* newNode(int data)
{
Node* node = new Node();
node->val = data;
node->left = node->right = NULL;
return node;
}
// helper fun to check leafnode
bool isleafnode(Node* root)
{
return !root->left && !root->right;
}
// fun checks whether the given BT is a full BT or not
bool isFullTree(Node* root)
{
// if tree is empty
if (!root)
return true;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
root = q.front();
q.pop();
// null indicates - not a full BT
if (root == NULL)
return false;
// if its not a leafnode then the current node
// should contain both left and right pointers.
if (!isleafnode(root)) {
q.push(root->left);
q.push(root->right);
}
}
return true;
}
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
if (isFullTree(root))
cout << "The Binary Tree is full\n";
else
cout << "The Binary Tree is not full\n";
return 0;
}
// This code is contributed by Modem Upendra. | linear | linear |
// C++ implementation to check whether a binary
// tree is a full binary tree or not
#include <bits/stdc++.h>
using namespace std;
// structure of a node of binary tree
struct Node {
int data;
Node *left, *right;
};
// function to get a new node
Node* getNode(int data)
{
// allocate space
Node* newNode = (Node*)malloc(sizeof(Node));
// put in the data
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// function to check whether a binary tree
// is a full binary tree or not
bool isFullBinaryTree(Node* root)
{
// if tree is empty
if (!root)
return true;
// queue used for level order traversal
queue<Node*> q;
// push 'root' to 'q'
q.push(root);
// traverse all the nodes of the binary tree
// level by level until queue is empty
while (!q.empty()) {
// get the pointer to 'node' at front
// of queue
Node* node = q.front();
q.pop();
// if it is a leaf node then continue
if (node->left == NULL && node->right == NULL)
continue;
// if either of the child is not null and the
// other one is null, then binary tree is not
// a full binary tee
if (node->left == NULL || node->right == NULL)
return false;
// push left and right childs of 'node'
// on to the queue 'q'
q.push(node->left);
q.push(node->right);
}
// binary tree is a full binary tee
return true;
}
// Driver program to test above
int main()
{
Node* root = getNode(1);
root->left = getNode(2);
root->right = getNode(3);
root->left->left = getNode(4);
root->left->right = getNode(5);
if (isFullBinaryTree(root))
cout << "Yes";
else
cout << "No";
return 0;
} | constant | linear |
// C++ program to check if a given binary tree is complete
// or not
#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;
struct node* right;
};
// Given a binary tree, return true if the tree is complete
// else false
bool isCompleteBT(node* root)
{
// Base Case: An empty tree is complete Binary Tree
if (root == NULL)
return true;
// Create an empty queue
// int rear, front;
// node **queue = createQueue(&front, &rear);
queue<node*> q;
q.push(root);
// Create a flag variable which will be set true when a
// non full node is seen
bool flag = false;
// Do level order traversal using queue.
// enQueue(queue, &rear, root);
while (!q.empty()) {
node* temp = q.front();
q.pop();
/* Check if left child is present*/
if (temp->left) {
// If we have seen a non full node, and we see a
// node with non-empty left child, then the
// given tree is not a complete Binary Tree
if (flag == true)
return false;
q.push(temp->left); // Enqueue Left Child
}
// If this a non-full node, set the flag as true
else
flag = true;
/* Check if right child is present*/
if (temp->right) {
// If we have seen a non full node, and we see a
// node with non-empty right child, then the
// given tree is not a complete Binary Tree
if (flag == true)
return false;
q.push(temp->right); // Enqueue Right Child
}
// If this a non-full node, set the flag as true
else
flag = true;
}
// If we reach here, then the tree is complete Binary
// Tree
return true;
}
/* 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()
{
/* Let us construct the following Binary Tree which
is not a complete Binary Tree
1
/ \
2 3
/ \ /
4 5 6
*/
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
if (isCompleteBT(root) == true)
cout << "Complete Binary Tree";
else
cout << "NOT Complete Binary Tree";
return 0;
}
// This code is contributed by Sania Kumari Gupta (kriSania804) | linear | linear |
/* Program to check if a given Binary Tree is balanced like a Red-Black Tree */
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int key;
Node *left, *right;
};
/* utility that allocates a new Node with the given key */
Node* newNode(int key)
{
Node* node = new Node;
node->key = key;
node->left = node->right = NULL;
return (node);
}
// Returns returns tree if the Binary tree is balanced like a Red-Black
// tree. This function also sets value in maxh and minh (passed by
// reference). maxh and minh are set as maximum and minimum heights of root.
bool isBalancedUtil(Node *root, int &maxh, int &minh)
{
// Base case
if (root == NULL)
{
maxh = minh = 0;
return true;
}
int lmxh, lmnh; // To store max and min heights of left subtree
int rmxh, rmnh; // To store max and min heights of right subtree
// Check if left subtree is balanced, also set lmxh and lmnh
if (isBalancedUtil(root->left, lmxh, lmnh) == false)
return false;
// Check if right subtree is balanced, also set rmxh and rmnh
if (isBalancedUtil(root->right, rmxh, rmnh) == false)
return false;
// Set the max and min heights of this node for the parent call
maxh = max(lmxh, rmxh) + 1;
minh = min(lmnh, rmnh) + 1;
// See if this node is balanced
if (maxh <= 2*minh)
return true;
return false;
}
// A wrapper over isBalancedUtil()
bool isBalanced(Node *root)
{
int maxh, minh;
return isBalancedUtil(root, maxh, minh);
}
/* Driver program to test above functions*/
int main()
{
Node * root = newNode(10);
root->left = newNode(5);
root->right = newNode(100);
root->right->left = newNode(50);
root->right->right = newNode(150);
root->right->left->left = newNode(40);
isBalanced(root)? cout << "Balanced" : cout << "Not Balanced";
return 0;
} | linear | linear |
// C++ program to check if two trees are mirror
// of each other
#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;
Node* left, *right;
};
/* Given two trees, return true if they are
mirror of each other */
/*As function has to return bool value instead integer value*/
bool areMirror(Node* a, Node* b)
{
/* Base case : Both empty */
if (a==NULL && b==NULL)
return true;
// If only one is empty
if (a==NULL || b == NULL)
return false;
/* Both non-empty, compare them recursively
Note that in recursive calls, we pass left
of one tree and right of other tree */
return a->data == b->data &&
areMirror(a->left, b->right) &&
areMirror(a->right, b->left);
}
/* Helper function that allocates a new node */
Node* newNode(int data)
{
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return(node);
}
/* Driver program to test areMirror() */
int main()
{
Node *a = newNode(1);
Node *b = newNode(1);
a->left = newNode(2);
a->right = newNode(3);
a->left->left = newNode(4);
a->left->right = newNode(5);
b->left = newNode(3);
b->right = newNode(2);
b->right->left = newNode(5);
b->right->right = newNode(4);
areMirror(a, b)? cout << "Yes" : cout << "No";
return 0;
} | logn | linear |
// C++ implementation to check whether the two
// binary trees are mirrors of each other or not
#include <bits/stdc++.h>
using namespace std;
// structure of a node in binary tree
struct Node
{
int data;
struct Node *left, *right;
};
// Utility function to create and return
// a new node for a binary tree
struct Node* newNode(int data)
{
struct Node *temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// function to check whether the two binary trees
// are mirrors of each other or not
string areMirrors(Node *root1, Node *root2)
{
stack<Node*> st1, st2;
while (1)
{
// iterative inorder traversal of 1st tree and
// reverse inorder traversal of 2nd tree
while (root1 && root2)
{
// if the corresponding nodes in the two traversal
// have different data values, then they are not
// mirrors of each other.
if (root1->data != root2->data)
return "No";
st1.push(root1);
st2.push(root2);
root1 = root1->left;
root2 = root2->right;
}
// if at any point one root becomes null and
// the other root is not null, then they are
// not mirrors. This condition verifies that
// structures of tree are mirrors of each other.
if (!(root1 == NULL && root2 == NULL))
return "No";
if (!st1.empty() && !st2.empty())
{
root1 = st1.top();
root2 = st2.top();
st1.pop();
st2.pop();
/* we have visited the node and its left subtree.
Now, it's right subtree's turn */
root1 = root1->right;
/* we have visited the node and its right subtree.
Now, it's left subtree's turn */
root2 = root2->left;
}
// both the trees have been completely traversed
else
break;
}
// trees are mirrors of each other
return "Yes";
}
// Driver program to test above
int main()
{
// 1st binary tree formation
Node *root1 = newNode(1); /* 1 */
root1->left = newNode(3); /* / \ */
root1->right = newNode(2); /* 3 2 */
root1->right->left = newNode(5); /* / \ */
root1->right->right = newNode(4); /* 5 4 */
// 2nd binary tree formation
Node *root2 = newNode(1); /* 1 */
root2->left = newNode(2); /* / \ */
root2->right = newNode(3); /* 2 3 */
root2->left->left = newNode(4); /* / \ */
root2->left->right = newNode(5); /* 4 5 */
cout << areMirrors(root1, root2);
return 0;
} | linear | linear |
// C++ program to check if a given Binary
// Tree is symmetric or not
#include<bits/stdc++.h>
using namespace std;
// A Binary Tree Node
struct Node
{
int key;
struct Node* left, *right;
};
// Utility function to create new Node
Node *newNode(int key)
{
Node *temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
// Returns true if a tree is symmetric
// i.e. mirror image of itself
bool isSymmetric(struct Node* root)
{
if(root == NULL)
return true;
// If it is a single tree node, then
// it is a symmetric tree.
if(!root->left && !root->right)
return true;
queue <Node*> q;
// Add root to queue two times so that
// it can be checked if either one child
// alone is NULL or not.
q.push(root);
q.push(root);
// To store two nodes for checking their
// symmetry.
Node* leftNode, *rightNode;
while(!q.empty()){
// Remove first two nodes to check
// their symmetry.
leftNode = q.front();
q.pop();
rightNode = q.front();
q.pop();
// if both left and right nodes
// exist, but have different
// values--> inequality, return false
if(leftNode->key != rightNode->key){
return false;
}
// Push left child of left subtree node
// and right child of right subtree
// node in queue.
if(leftNode->left && rightNode->right){
q.push(leftNode->left);
q.push(rightNode->right);
}
// If only one child is present alone
// and other is NULL, then tree
// is not symmetric.
else if (leftNode->left || rightNode->right)
return false;
// Push right child of left subtree node
// and left child of right subtree node
// in queue.
if(leftNode->right && rightNode->left){
q.push(leftNode->right);
q.push(rightNode->left);
}
// If only one child is present alone
// and other is NULL, then tree
// is not symmetric.
else if(leftNode->right || rightNode->left)
return false;
}
return true;
}
// Driver program
int main()
{
// Let us construct the Tree shown in
// the above figure
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(4);
root->right->right = newNode(3);
if(isSymmetric(root))
cout << "The given tree is Symmetric";
else
cout << "The given tree is not Symmetric";
return 0;
}
// This code is contributed by Nikhil jindal. | logn | linear |
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has key, pointer to left
child and a pointer to right child */
struct Node {
int key;
struct Node *left, *right;
};
/* To create a newNode of tree and return pointer */
struct Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
// Takes two parameters - same initially and
// calls recursively
void printMiddleLevelUtil(Node* a, Node* b)
{
// Base case e
if (a == NULL || b == NULL)
return;
// Fast pointer has reached the leaf so print
// value at slow pointer
if ((b->left == NULL) && (b->right == NULL)) {
cout << a->key << " ";
return;
}
// Recursive call
// root.left.left and root.left.right will
// print same value
// root.right.left and root.right.right
// will print same value
// So we use any one of the condition
if (b->left->left) {
printMiddleLevelUtil(a->left, b->left->left);
printMiddleLevelUtil(a->right, b->left->left);
}
else {
printMiddleLevelUtil(a->left, b->left);
printMiddleLevelUtil(a->right, b->left);
}
}
// Main printing method that take a Tree as input
void printMiddleLevel(Node* node)
{
printMiddleLevelUtil(node, node);
}
// Driver program to test above functions
int main()
{
Node* n1 = newNode(1);
Node* n2 = newNode(2);
Node* n3 = newNode(3);
Node* n4 = newNode(4);
Node* n5 = newNode(5);
Node* n6 = newNode(6);
Node* n7 = newNode(7);
n2->left = n4;
n2->right = n5;
n3->left = n6;
n3->right = n7;
n1->left = n2;
n1->right = n3;
printMiddleLevel(n1);
}
// This code is contributed by Prasad Kshirsagar | logn | linear |
// 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;
} | linear | nlogn |
// 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 untill 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 | linear | linear |
// C++ program to print all root to leaf paths
// with there relative position
#include<bits/stdc++.h>
using namespace std;
#define MAX_PATH_SIZE 1000
// tree structure
struct Node
{
char data;
Node *left, *right;
};
// function create new node
Node * newNode(char data)
{
struct Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// store path information
struct PATH
{
int Hd; // horizontal distance of node from root.
char key; // store key
};
// Prints given root to leaf path with underscores
void printPath(vector < PATH > path, int size)
{
// Find the minimum horizontal distance value
// in current root to leaf path
int minimum_Hd = INT_MAX;
PATH p;
// find minimum horizontal distance
for (int it=0; it<size; it++)
{
p = path[it];
minimum_Hd = min(minimum_Hd, p.Hd);
}
// print the root to leaf path with "_"
// that indicate the related position
for (int it=0; it < size; it++)
{
// current tree node
p = path[it];
int noOfUnderScores = abs(p.Hd - minimum_Hd);
// print underscore
for (int i = 0; i < noOfUnderScores; i++)
cout << "_ ";
// print current key
cout << p.key << endl;
}
cout << "==============================" << endl;
}
// a utility function print all path from root to leaf
// working of this function is similar to function of
// "Print_vertical_order" : Print paths of binary tree
// in vertical order
// https://www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/
void printAllPathsUtil(Node *root,
vector < PATH > &AllPath,
int HD, int order )
{
// base case
if(root == NULL)
return;
// leaf node
if (root->left == NULL && root->right == NULL)
{
// add leaf node and then print path
AllPath[order] = (PATH { HD, root->data });
printPath(AllPath, order+1);
return;
}
// store current path information
AllPath[order] = (PATH { HD, root->data });
// call left sub_tree
printAllPathsUtil(root->left, AllPath, HD-1, order+1);
//call left sub_tree
printAllPathsUtil(root->right, AllPath, HD+1, order+1);
}
void printAllPaths(Node *root)
{
// base case
if (root == NULL)
return;
vector<PATH> Allpaths(MAX_PATH_SIZE);
printAllPathsUtil(root, Allpaths, 0, 0);
}
// Driver program to test above function
int main()
{
Node *root = newNode('A');
root->left = newNode('B');
root->right = newNode('C');
root->left->left = newNode('D');
root->left->right = newNode('E');
root->right->left = newNode('F');
root->right->right = newNode('G');
printAllPaths(root);
return 0;
} | logn | constant |
// Recursive C++ program to print odd level nodes
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left, *right;
};
void printOddNodes(Node *root, bool isOdd = true)
{
// If empty tree
if (root == NULL)
return;
// If current node is of odd level
if (isOdd)
cout << root->data << " " ;
// Recur for children with isOdd
// switched.
printOddNodes(root->left, !isOdd);
printOddNodes(root->right, !isOdd);
}
// Utility method to create a node
struct Node* newNode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Driver code
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printOddNodes(root);
return 0;
} | linear | linear |
// Iterative C++ program to print odd level nodes
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left, *right;
};
// Iterative method to do level order traversal line by line
void printOddNodes(Node *root)
{
// Base Case
if (root == NULL) return;
// Create an empty queue for level
// order traversal
queue<Node *> q;
// Enqueue root and initialize level as odd
q.push(root);
bool isOdd = true;
while (1)
{
// nodeCount (queue size) indicates
// number of nodes at current level.
int nodeCount = q.size();
if (nodeCount == 0)
break;
// Dequeue all nodes of current level
// and Enqueue all nodes of next level
while (nodeCount > 0)
{
Node *node = q.front();
if (isOdd)
cout << node->data << " ";
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
nodeCount--;
}
isOdd = !isOdd;
}
}
// Utility method to create a node
struct Node* newNode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Driver code
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printOddNodes(root);
return 0;
} | linear | linear |
// A C++ program to find the all full nodes in
// a given binary tree
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *left, *right;
};
Node *newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Traverses given tree in Inorder fashion and
// prints all nodes that have both children as
// non-empty.
void findFullNode(Node *root)
{
if (root != NULL)
{
findFullNode(root->left);
if (root->left != NULL && root->right != NULL)
cout << root->data << " ";
findFullNode(root->right);
}
}
// Driver program to test above function
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->right = newNode(7);
root->right->right->right = newNode(8);
root->right->left->right->left = newNode(9);
findFullNode(root);
return 0;
} | linear | linear |
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
struct Node {
int key;
struct Node *left, *right;
};
// Utility function to create a new node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
/*Function to find sum of all elements*/
int sumBT(Node* root)
{
//sum variable to track the sum of
//all variables.
int sum = 0;
queue<Node*> q;
//Pushing the first level.
q.push(root);
//Pushing elements at each level from
//the tree.
while (!q.empty()) {
Node* temp = q.front();
q.pop();
//After popping each element from queue
//add its data to the sum variable.
sum += temp->key;
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
}
return sum;
}
// Driver program
int main()
{
// Let us create Binary Tree shown in above example
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
cout << "Sum of all elements in the binary tree is: "
<< sumBT(root);
}
//This code is contributed by Sarthak Delori | linear | linear |
// C++ implementation to find the sum of all
// the parent nodes having child node x
#include <bits/stdc++.h>
using namespace std;
// Node of a binary tree
struct Node
{
int data;
Node *left, *right;
};
// function to get a new node
Node* getNode(int data)
{
// allocate memory for the node
Node *newNode =
(Node*)malloc(sizeof(Node));
// put in the data
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// function to find the sum of all the
// parent nodes having child node x
void sumOfParentOfX(Node* root, int& sum, int x)
{
// if root == NULL
if (!root)
return;
// if left or right child of root is 'x', then
// add the root's data to 'sum'
if ((root->left && root->left->data == x) ||
(root->right && root->right->data == x))
sum += root->data;
// recursively find the required parent nodes
// in the left and right subtree
sumOfParentOfX(root->left, sum, x);
sumOfParentOfX(root->right, sum, x);
}
// utility function to find the sum of all
// the parent nodes having child node x
int sumOfParentOfXUtil(Node* root, int x)
{
int sum = 0;
sumOfParentOfX(root, sum, x);
// required sum of parent nodes
return sum;
}
// Driver program to test above
int main()
{
// binary tree formation
Node *root = getNode(4); /* 4 */
root->left = getNode(2); /* / \ */
root->right = getNode(5); /* 2 5 */
root->left->left = getNode(7); /* / \ / \ */
root->left->right = getNode(2); /* 7 2 2 3 */
root->right->left = getNode(2);
root->right->right = getNode(3);
int x = 2;
cout << "Sum = "
<< sumOfParentOfXUtil(root, x);
return 0;
} | linear | linear |
// CPP program to find total sum
// of right leaf nodes
#include <bits/stdc++.h>
using namespace std;
// struct node of binary tree
struct Node {
int data;
Node *left, *right;
};
// return new node
Node* addNode(int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// utility function to calculate sum
// of right leaf nodes
void rightLeafSum(Node* root, int& sum)
{
if (!root)
return;
// check if the right child of root
// is leaf node
if (root->right)
if (root->right->left == NULL
&& root->right->right == NULL)
sum += root->right->data;
rightLeafSum(root->left, sum);
rightLeafSum(root->right, sum);
}
// driver program
int main()
{
// construct binary tree
Node* root = addNode(1);
root->left = addNode(2);
root->left->left = addNode(4);
root->left->right = addNode(5);
root->left->left->right = addNode(2);
root->right = addNode(3);
root->right->right = addNode(8);
root->right->right->left = addNode(6);
root->right->right->right = addNode(7);
// variable to store sum of right
// leaves
int sum = 0;
rightLeafSum(root, sum);
cout << sum << endl;
return 0;
} | logn | linear |
// C++ program to find total sum of right leaf nodes.
#include <bits/stdc++.h>
using namespace std;
// struct node of Binary Tree
struct Node {
int data;
Node *left, *right;
};
// fun to create and return a new node
Node* addNode(int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// fun to calculate sum of right leaf nodes
int rightLeafSum(Node* root, bool isrightleaf)
{
// base case
if (!root)
return 0;
// if it is a leaf node and right node, the return
// root's data.
if (!root->left && !root->right && isrightleaf)
return root->data;
// recur of left subtree and right subtree and do the
// summation simultaniously.
return rightLeafSum(root->left, false)
+ rightLeafSum(root->right, true);
}
int main()
{
// create a tree
Node* root = addNode(1);
root->left = addNode(2);
root->left->left = addNode(4);
root->left->right = addNode(5);
root->left->left->right = addNode(2);
root->right = addNode(3);
root->right->right = addNode(8);
root->right->right->left = addNode(6);
root->right->right->right = addNode(7);
cout << rightLeafSum(root, false);
return 0;
}
// This code is contributed by Modem Upendra | logn | linear |
// CPP program to find total sum
// of right leaf nodes
#include <bits/stdc++.h>
using namespace std;
// struct node of binary tree
struct Node {
int data;
Node *left, *right;
};
// return new node
Node* addNode(int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// utility function to calculate sum
// of right leaf nodes iteratively
int rightLeafSum(Node* root)
{
// declaring sum to store sum of right leaves
int sum = 0;
// queue of Node* type
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* curr = q.front();
q.pop();
// check for left node
if (curr->left) {
q.push(curr->left);
}
// check for right node
if (curr->right) {
// check for right leaf node
if (curr->right->right == NULL
and curr->right->left == NULL) {
// incrementing sum for found right leaf
// node
sum += curr->right->data;
}
q.push(curr->right);
}
}
return sum;
}
// driver program
int main()
{
// construct binary tree
Node* root = addNode(1);
root->left = addNode(2);
root->left->left = addNode(4);
root->left->right = addNode(5);
root->left->left->right = addNode(2);
root->right = addNode(3);
root->right->right = addNode(8);
root->right->right->left = addNode(6);
root->right->right->right = addNode(7);
int sum = rightLeafSum(root);
cout << sum << endl;
return 0;
} | np | linear |
#include <bits/stdc++.h>
using namespace std;
//Building a tree node having left and right pointers set to null initially
struct Node
{
Node* left;
Node* right;
int data;
//constructor to set the data of the newly created tree node
Node(int element){
data = element;
this->left = nullptr;
this->right = nullptr;
}
};
int longestPathLeaf(Node* root){
/* structure to store current Node,it's level and sum in the path*/
struct Element{
Node* data;
int level;
int sum;
};
/*
maxSumLevel stores maximum sum so far in the path
maxLevel stores maximum level so far
*/
int maxSumLevel = root->data,maxLevel = 0;
/* queue to implement level order traversal */
list<Element> que;
Element e;
/* Each element variable stores the current Node, it's level, sum in the path */
e.data = root;
e.level = 0;
e.sum = root->data;
/* push the root element*/
que.push_back(e);
/* do level order traversal on the tree*/
while(!que.empty()){
Element front = que.front();
Node* curr = front.data;
que.pop_front();
/* if the level of current front element is greater than the maxLevel so far then update maxSum*/
if(front.level > maxLevel){
maxSumLevel = front.sum;
maxLevel = front.level;
}
/* if another path competes then update if the sum is greater than the previous path of same height*/
else if(front.level == maxLevel && front.sum > maxSumLevel)
maxSumLevel = front.sum;
/* push the left element if exists*/
if(curr->left){
e.data = curr->left;
e.sum = e.data->data;
e.sum += front.sum;
e.level = front.level+1;
que.push_back(e);
}
/*push the right element if exists*/
if(curr->right){
e.data = curr->right;
e.sum = e.data->data;
e.sum += front.sum;
e.level = front.level+1;
que.push_back(e);
}
}
/*return the answer*/
return maxSumLevel;
}
//Helper function
int main() {
Node* root = new Node(4);
root->left = new Node(2);
root->right = new Node(5);
root->left->left = new Node(7);
root->left->right = new Node(1);
root->right->left = new Node(2);
root->right->right = new Node(3);
root->left->right->left = new Node(6);
cout << longestPathLeaf(root) << "\n";
return 0;
} | linear | linear |
// C++ program to find maximum path
//sum between two leaves of a binary tree
#include <bits/stdc++.h>
using namespace std;
// A binary tree node
struct Node
{
int data;
struct Node* left, *right;
};
// Utility function to allocate memory for a new node
struct Node* newNode(int data)
{
struct Node* node = new(struct Node);
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Utility function to find maximum of two integers
int max(int a, int b)
{ return (a >= b)? a: b; }
// A utility function to find the maximum sum between any
// two leaves.This function calculates two values:
// 1) Maximum path sum between two leaves which is stored
// in res.
// 2) The maximum root to leaf path sum which is returned.
// If one side of root is empty, then it returns INT_MIN
int maxPathSumUtil(struct Node *root, int &res)
{
// Base cases
if (root==NULL) return 0;
if (!root->left && !root->right) return root->data;
// Find maximum sum in left and right subtree. Also
// find maximum root to leaf sums in left and right
// subtrees and store them in ls and rs
int ls = maxPathSumUtil(root->left, res);
int rs = maxPathSumUtil(root->right, res);
// If both left and right children exist
if (root->left && root->right)
{
// Update result if needed
res = max(res, ls + rs + root->data);
// Return maximum possible value for root being
// on one side
return max(ls, rs) + root->data;
}
// If any of the two children is empty, return
// root sum for root being on one side
return (!root->left)? rs + root->data:
ls + root->data;
}
// The main function which returns sum of the maximum
// sum path between two leaves. This function mainly
// uses maxPathSumUtil()
int maxPathSum(struct Node *root)
{
int res = INT_MIN;
int val = maxPathSumUtil(root, res);
//--- for test case ---
// 7
// / \
// Null -3
// (case - 1)
// value of res will be INT_MIN but the answer is 4 , which is returned by the
// function maxPathSumUtil().
if(root->left && root->right)
return res;
return max(res, val);
}
// Driver Code
int main()
{
struct Node *root = newNode(-15);
root->left = newNode(5);
root->right = newNode(6);
root->left->left = newNode(-8);
root->left->right = newNode(1);
root->left->left->left = newNode(2);
root->left->left->right = newNode(6);
root->right->left = newNode(3);
root->right->right = newNode(9);
root->right->right->right= newNode(0);
root->right->right->right->left= newNode(4);
root->right->right->right->right= newNode(-1);
root->right->right->right->right->left= newNode(10);
cout << "Max pathSum of the given binary tree is "
<< maxPathSum(root);
return 0;
} | linear | linear |
// C++ program to print all paths with sum k.
#include <bits/stdc++.h>
using namespace std;
// utility function to print contents of
// a vector from index i to it's end
void printVector(const vector<int>& v, int i)
{
for (int j = i; j < v.size(); j++)
cout << v[j] << " ";
cout << endl;
}
// binary tree node
struct Node {
int data;
Node *left, *right;
Node(int x)
{
data = x;
left = right = NULL;
}
};
// This function prints all paths that have sum k
void printKPathUtil(Node* root, vector<int>& path, int k)
{
// empty node
if (!root)
return;
// add current node to the path
path.push_back(root->data);
// check if there's any k sum path
// in the left sub-tree.
printKPathUtil(root->left, path, k);
// check if there's any k sum path
// in the right sub-tree.
printKPathUtil(root->right, path, k);
// check if there's any k sum path that
// terminates at this node
// Traverse the entire path as
// there can be negative elements too
int f = 0;
for (int j = path.size() - 1; j >= 0; j--) {
f += path[j];
// If path sum is k, print the path
if (f == k)
printVector(path, j);
}
// Remove the current element from the path
path.pop_back();
}
// A wrapper over printKPathUtil()
void printKPath(Node* root, int k)
{
vector<int> path;
printKPathUtil(root, path, k);
}
// Driver code
int main()
{
Node* root = new Node(1);
root->left = new Node(3);
root->left->left = new Node(2);
root->left->right = new Node(1);
root->left->right->left = new Node(1);
root->right = new Node(-1);
root->right->left = new Node(4);
root->right->left->left = new Node(1);
root->right->left->right = new Node(2);
root->right->right = new Node(5);
root->right->right->right = new Node(2);
int k = 5;
printKPath(root, k);
return 0;
} | logn | linear |
// C++ program to find if there is a subtree with
// given sum
#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;
};
/* utility that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newnode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// function to check if there exist any subtree with given sum
// cur_sum --> sum of current subtree from ptr as root
// sum_left --> sum of left subtree from ptr as root
// sum_right --> sum of right subtree from ptr as root
bool sumSubtreeUtil(struct Node *ptr, int *cur_sum, int sum)
{
// base condition
if (ptr == NULL)
{
*cur_sum = 0;
return false;
}
// Here first we go to left sub-tree, then right subtree
// then first we calculate sum of all nodes of subtree
// having ptr as root and assign it as cur_sum
// cur_sum = sum_left + sum_right + ptr->data
// after that we check if cur_sum == sum
int sum_left = 0, sum_right = 0;
return ( sumSubtreeUtil(ptr->left, ∑_left, sum) ||
sumSubtreeUtil(ptr->right, ∑_right, sum) ||
((*cur_sum = sum_left + sum_right + ptr->data) == sum));
}
// Wrapper over sumSubtreeUtil()
bool sumSubtree(struct Node *root, int sum)
{
// Initialize sum of subtree with root
int cur_sum = 0;
return sumSubtreeUtil(root, &cur_sum, sum);
}
// driver program to run the case
int main()
{
struct Node *root = newnode(8);
root->left = newnode(5);
root->right = newnode(4);
root->left->left = newnode(9);
root->left->right = newnode(7);
root->left->right->left = newnode(1);
root->left->right->right = newnode(12);
root->left->right->right->right = newnode(2);
root->right->right = newnode(11);
root->right->right->left = newnode(3);
int sum = 22;
if (sumSubtree(root, sum))
cout << "Yes";
else
cout << "No";
return 0;
} | logn | linear |
// C++ implementation to count subtrees that
// sum up to a given value x
#include <bits/stdc++.h>
using namespace std;
// structure of a node of binary tree
struct Node {
int data;
Node *left, *right;
};
// function to get a new node
Node* getNode(int data)
{
// allocate space
Node* newNode = (Node*)malloc(sizeof(Node));
// put in the data
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// function to count subtrees that
// sum up to a given value x
int countSubtreesWithSumX(Node* root, int& count, int x)
{
// if tree is empty
if (!root)
return 0;
// sum of nodes in the left subtree
int ls = countSubtreesWithSumX(root->left, count, x);
// sum of nodes in the right subtree
int rs = countSubtreesWithSumX(root->right, count, x);
// sum of nodes in the subtree rooted
// with 'root->data'
int sum = ls + rs + root->data;
// if true
if (sum == x)
count++;
// return subtree's nodes sum
return sum;
}
// utility function to count subtrees that
// sum up to a given value x
int countSubtreesWithSumXUtil(Node* root, int x)
{
// if tree is empty
if (!root)
return 0;
int count = 0;
// sum of nodes in the left subtree
int ls = countSubtreesWithSumX(root->left, count, x);
// sum of nodes in the right subtree
int rs = countSubtreesWithSumX(root->right, count, x);
// if tree's nodes sum == x
if ((ls + rs + root->data) == x)
count++;
// required count of subtrees
return count;
}
// Driver program to test above
int main()
{
/* binary tree creation
5
/ \
-10 3
/ \ / \
9 8 -4 7
*/
Node* root = getNode(5);
root->left = getNode(-10);
root->right = getNode(3);
root->left->left = getNode(9);
root->left->right = getNode(8);
root->right->left = getNode(-4);
root->right->right = getNode(7);
int x = 7;
cout << "Count = "
<< countSubtreesWithSumXUtil(root, x);
return 0;
} | logn | linear |
// C++ program to find if
// there is a subtree with
// given sum
#include <bits/stdc++.h>
using namespace std;
// Structure of a node of binary tree
struct Node {
int data;
Node *left, *right;
};
// Function to get a new node
Node* getNode(int data)
{
// Allocate space
Node* newNode = (Node*)malloc(sizeof(Node));
// Put in the data
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// Utility function to count subtrees that
// sum up to a given value x
int countSubtreesWithSumXUtil(Node* root, int x)
{
static int count = 0;
static Node* ptr = root;
int l = 0, r = 0;
if (root == NULL)
return 0;
l += countSubtreesWithSumXUtil(root->left, x);
r += countSubtreesWithSumXUtil(root->right, x);
if (l + r + root->data == x)
count++;
if (ptr != root)
return l + root->data + r;
return count;
}
// Driver code
int main()
{
/* binary tree creation
5
/ \
-10 3
/ \ / \
9 8 -4 7
*/
Node* root = getNode(5);
root->left = getNode(-10);
root->right = getNode(3);
root->left->left = getNode(9);
root->left->right = getNode(8);
root->right->left = getNode(-4);
root->right->right = getNode(7);
int x = 7;
cout << "Count = "
<< countSubtreesWithSumXUtil(root, x);
return 0;
}
// This code is contributed by Sadik Ali | logn | linear |
// C++ implementation to find maximum spiral sum
#include <bits/stdc++.h>
using namespace std;
// structure of a node of binary tree
struct Node {
int data;
Node *left, *right;
};
// A utility function to create a new node
Node* newNode(int data)
{
// allocate space
Node* node = new Node;
// put in the data
node->data = data;
node->left = node->right = NULL;
return node;
}
// function to find the maximum sum contiguous subarray.
// implements kadane's algorithm
int maxSum(vector<int> arr, int n)
{
// to store the maximum value that is ending
// up to the current index
int max_ending_here = INT_MIN;
// to store the maximum value encountered so far
int max_so_far = INT_MIN;
// traverse the array elements
for (int i = 0; i < n; i++) {
// if max_ending_here < 0, then it could
// not possibly contribute to the maximum
// sum further
if (max_ending_here < 0)
max_ending_here = arr[i];
// else add the value arr[i] to max_ending_here
else
max_ending_here += arr[i];
// update max_so_far
max_so_far = max(max_so_far, max_ending_here);
}
// required maximum sum contiguous subarray value
return max_so_far;
}
// function to find maximum spiral sum
int maxSpiralSum(Node* root)
{
// if tree is empty
if (root == NULL)
return 0;
// Create two stacks to store alternate levels
stack<Node*> s1; // For levels from right to left
stack<Node*> s2; // For levels from left to right
// vector to store spiral order traversal
// of the binary tree
vector<int> arr;
// Push first level to first stack 's1'
s1.push(root);
// traversing tree in spiral form until
// there are elements in any one of the
// stacks
while (!s1.empty() || !s2.empty()) {
// traverse current level from s1 and
// push nodes of next level to s2
while (!s1.empty()) {
Node* temp = s1.top();
s1.pop();
// push temp-data to 'arr'
arr.push_back(temp->data);
// Note that right is pushed before left
if (temp->right)
s2.push(temp->right);
if (temp->left)
s2.push(temp->left);
}
// traverse current level from s2 and
// push nodes of next level to s1
while (!s2.empty()) {
Node* temp = s2.top();
s2.pop();
// push temp-data to 'arr'
arr.push_back(temp->data);
// Note that left is pushed before right
if (temp->left)
s1.push(temp->left);
if (temp->right)
s1.push(temp->right);
}
}
// required maximum spiral sum
return maxSum(arr, arr.size());
}
// Driver program to test above
int main()
{
Node* root = newNode(-2);
root->left = newNode(-3);
root->right = newNode(4);
root->left->left = newNode(5);
root->left->right = newNode(1);
root->right->left = newNode(-2);
root->right->right = newNode(-1);
root->left->left->left = newNode(-3);
root->right->right->right = newNode(2);
cout << "Maximum Spiral Sum = "
<< maxSpiralSum(root);
return 0;
} | linear | linear |
// C++ implementation to find the sum of
// leaf nodes at minimum level
#include <bits/stdc++.h>
using namespace std;
// structure of a node of binary tree
struct Node {
int data;
Node *left, *right;
};
// function to get a new node
Node* getNode(int data)
{
// allocate space
Node* newNode = (Node*)malloc(sizeof(Node));
// put in the data
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// function to find the sum of
// leaf nodes at minimum level
int sumOfLeafNodesAtMinLevel(Node* root)
{
// if tree is empty
if (!root)
return 0;
// if there is only one node
if (!root->left && !root->right)
return root->data;
// queue used for level order traversal
queue<Node*> q;
int sum = 0;
bool f = 0;
// push root node in the queue 'q'
q.push(root);
while (f == 0) {
// count number of nodes in the
// current level
int nc = q.size();
// traverse the current level nodes
while (nc--) {
// get front element from 'q'
Node* top = q.front();
q.pop();
// if it is a leaf node
if (!top->left && !top->right) {
// accumulate data to 'sum'
sum += top->data;
// set flag 'f' to 1, to signify
// minimum level for leaf nodes
// has been encountered
f = 1;
}
else {
// if top's left and right child
// exists, then push them to 'q'
if (top->left)
q.push(top->left);
if (top->right)
q.push(top->right);
}
}
}
// required sum
return sum;
}
// Driver program to test above
int main()
{
// binary tree creation
Node* root = getNode(1);
root->left = getNode(2);
root->right = getNode(3);
root->left->left = getNode(4);
root->left->right = getNode(5);
root->right->left = getNode(6);
root->right->right = getNode(7);
root->left->right->left = getNode(8);
root->right->left->right = getNode(9);
cout << "Sum = "
<< sumOfLeafNodesAtMinLevel(root);
return 0;
} | linear | linear |
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
// function to get a new node
Node* getNode(int data)
{
// allocate space
Node* newNode = (Node*)malloc(sizeof(Node));
// put in the data
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
map <int, vector <int>> mp;
void solve(Node* root, int level) {
if(root == NULL)
return;
if(root->left == NULL && root->right == NULL)
mp[level].push_back(root->data);
solve(root->left, level+1);
solve(root->right, level+1);
}
int minLeafSum(Node *root)
{
solve(root, 0);
int sum = 0;
for(auto i:mp) {
for(auto j:i.second) {
sum += j;
}
return sum;
}
}
int main() {
// binary tree creation
Node* root = getNode(1);
root->left = getNode(2);
root->right = getNode(3);
root->left->left = getNode(4);
root->left->right = getNode(5);
root->right->left = getNode(6);
root->right->right = getNode(7);
cout << "Sum = "<< minLeafSum(root);
return 0;
} | linear | linear |
#include <bits/stdc++.h>
using namespace std;
#define bool int
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class node {
public:
int data;
node* left;
node* right;
};
/*
Given a tree and a sum, return true if there is a path from
the root down to a leaf, such that adding up all the values
along the path equals the given sum.
Strategy: subtract the node value from the sum when
recurring down, and check to see if the sum is 0 when you
when you reach the leaf node.
*/
bool hasPathSum(node* Node, int sum)
{
if (Node == NULL)
return 0;
bool ans = 0;
int subSum = sum - Node->data;
/* If we reach a leaf node and sum becomes 0 then return
* true*/
if (subSum == 0 && Node->left == NULL
&& Node->right == NULL)
return 1;
/* otherwise check both subtrees */
if (Node->left)
ans = ans || hasPathSum(Node->left, subSum);
if (Node->right)
ans = ans || hasPathSum(Node->right, subSum);
return ans;
}
/* UTILITY FUNCTIONS */
/* 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 = NULL;
Node->right = NULL;
return (Node);
}
// Driver's Code
int main()
{
int sum = 21;
/* 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);
// Function call
if (hasPathSum(root, sum))
cout << "There is a root-to-leaf path with sum "
<< sum;
else
cout << "There is no root-to-leaf path with sum "
<< sum;
return 0;
}
// This code is contributed by rathbhupendra | logn | linear |
// C++ program to find sum of all paths from root to leaves
// A Binary tree node
#include <bits/stdc++.h>
using namespace std;
// A Binary tree node
class Node
{
public:
int data;
Node *left, *right;
// Constructor to create a new node
Node(int val)
{
data = val;
left = right = NULL;
}
};
void treePathsSumUtil(Node* root, vector<string> currPath,
vector<vector<string>> &allPath)
{
// Base Case
if (root == NULL)
return;
// append the root data in string format in currPath
currPath.push_back((to_string)(root->data));
// if we found a leaf node we copy the currPath to allPath
if (root->left == NULL && root->right == NULL)
allPath.push_back(currPath);
// traverse in the left subtree
treePathsSumUtil(root->left, currPath, allPath);
// traverse in the right subtree
treePathsSumUtil(root->right, currPath, allPath);
// remove the current element from the path
currPath.pop_back();
}
int treePathsSum(Node* root)
{
// store all the root to leaf path in allPath
vector<vector<string>> allPath;
vector<string> v;
treePathsSumUtil(root, v, allPath);
// store the sum
int s = 0;
for(auto pathNumber : allPath)
{
string k="";
// join the pathNumbers to convert them
// into the number to calculate sum
for(auto x: pathNumber)
k = k+x;
s += stoi(k);
}
return s;
}
// Driver code
int main()
{
Node *root = new Node(6);
root->left = new Node(3);
root->right = new Node(5);
root->left->left = new Node(2);
root->left->right = new Node(5);
root->right->right = new Node(4);
root->left->right->left = new Node(7);
root->left->right->right = new Node(4);
cout<<"Sum of all paths is "<<treePathsSum(root);
return 0;
}
// This code is contributed by Abhijeet Kumar(abhijeet19403) | linear | quadratic |
// Find root of tree where children
// sum for every node id is given.
#include<bits/stdc++.h>
using namespace std;
int findRoot(pair<int, int> arr[], int n)
{
// Every node appears once as an id, and
// every node except for the root appears
// once in a sum. So if we subtract all
// the sums from all the ids, we're left
// with the root id.
int root = 0;
for (int i=0; i<n; i++)
root += (arr[i].first - arr[i].second);
return root;
}
// Driver code
int main()
{
pair<int, int> arr[] = {{1, 5}, {2, 0},
{3, 0}, {4, 0}, {5, 5}, {6, 5}};
int n = sizeof(arr)/sizeof(arr[0]);
printf("%d\n", findRoot(arr, n));
return 0;
} | constant | linear |
// C++ implementation to replace each node
// in binary tree with the sum of its inorder
// predecessor and successor
#include <bits/stdc++.h>
using namespace std;
// node of a binary tree
struct Node {
int data;
struct Node* left, *right;
};
// function to get a new node of a binary tree
struct Node* getNode(int data)
{
// allocate node
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
// put in the data;
new_node->data = data;
new_node->left = new_node->right = NULL;
return new_node;
}
// function to store the inorder traversal
// of the binary tree in 'arr'
void storeInorderTraversal(struct Node* root,
vector<int>& arr)
{
// if root is NULL
if (!root)
return;
// first recur on left child
storeInorderTraversal(root->left, arr);
// then store the root's data in 'arr'
arr.push_back(root->data);
// now recur on right child
storeInorderTraversal(root->right, arr);
}
// function to replace each node with the sum of its
// inorder predecessor and successor
void replaceNodeWithSum(struct Node* root,
vector<int> arr, int* i)
{
// if root is NULL
if (!root)
return;
// first recur on left child
replaceNodeWithSum(root->left, arr, i);
// replace node's data with the sum of its
// inorder predecessor and successor
root->data = arr[*i - 1] + arr[*i + 1];
// move 'i' to point to the next 'arr' element
++*i;
// now recur on right child
replaceNodeWithSum(root->right, arr, i);
}
// Utility function to replace each node in binary
// tree with the sum of its inorder predecessor
// and successor
void replaceNodeWithSumUtil(struct Node* root)
{
// if tree is empty
if (!root)
return;
vector<int> arr;
// store the value of inorder predecessor
// for the leftmost leaf
arr.push_back(0);
// store the inorder traversal of the tree in 'arr'
storeInorderTraversal(root, arr);
// store the value of inorder successor
// for the rightmost leaf
arr.push_back(0);
// replace each node with the required sum
int i = 1;
replaceNodeWithSum(root, arr, &i);
}
// function to print the preorder traversal
// of a binary tree
void preorderTraversal(struct Node* root)
{
// if root is NULL
if (!root)
return;
// first print the data of node
cout << root->data << " ";
// then recur on left subtree
preorderTraversal(root->left);
// now recur on right subtree
preorderTraversal(root->right);
}
// Driver program to test above
int main()
{
// binary tree formation
struct Node* root = getNode(1); /* 1 */
root->left = getNode(2); /* / \ */
root->right = getNode(3); /* 2 3 */
root->left->left = getNode(4); /* / \ / \ */
root->left->right = getNode(5); /* 4 5 6 7 */
root->right->left = getNode(6);
root->right->right = getNode(7);
cout << "Preorder Traversal before tree modification:n";
preorderTraversal(root);
replaceNodeWithSumUtil(root);
cout << "\nPreorder Traversal after tree modification:n";
preorderTraversal(root);
return 0;
} | linear | linear |
// C++ implementation to replace each node
// in binary tree with the sum of its inorder
// predecessor and successor
#include <bits/stdc++.h>
using namespace std;
// node of a binary tree
struct Node {
int data;
struct Node* left, *right;
};
// function to get a new node of a binary tree
struct Node* getNode(int data)
{
// allocate node
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
// put in the data;
new_node->data = data;
new_node->left = new_node->right = NULL;
return new_node;
}
// function to print the preorder traversal
// of a binary tree
void preorderTraversal(struct Node* root)
{
// if root is NULL
if (!root)
return;
// first print the data of node
cout << root->data << " ";
// then recur on left subtree
preorderTraversal(root->left);
// now recur on right subtree
preorderTraversal(root->right);
}
void inOrderTraverse(struct Node* root, struct Node* &prev, int &prevVal)
{
if(root == NULL) return;
inOrderTraverse(root->left, prev, prevVal);
if(prev == NULL)
{
prev = root;
prevVal = 0;
}
else
{
int temp = prev->data;
prev->data = prevVal + root->data;
prev = root;
prevVal = temp;
}
inOrderTraverse(root->right, prev, prevVal);
}
// Driver program to test above
int main()
{
// binary tree formation
struct Node* root = getNode(1); /* 1 */
root->left = getNode(2); /* / \ */
root->right = getNode(3); /* 2 3 */
root->left->left = getNode(4); /* / \ / \ */
root->left->right = getNode(5); /* 4 5 6 7 */
root->right->left = getNode(6);
root->right->right = getNode(7);
cout << "Preorder Traversal before tree modification:\n";
preorderTraversal(root);
struct Node* prev = NULL;
int prevVal = -1;
inOrderTraverse(root, prev, prevVal);
// update righmost node.
prev->data = prevVal;
cout << "\nPreorder Traversal after tree modification:\n";
preorderTraversal(root);
return 0;
} | linear | linear |
// C++ Program for Lowest Common Ancestor
// in a Binary Tree
// A O(n) solution to find LCA
// of two given values n1 and n2
#include <bits/stdc++.h>
using namespace std;
// A Binary Tree node
struct Node {
int key;
struct Node *left, *right;
};
// Utility function creates a new binary tree node with
// given key
Node* newNode(int k)
{
Node* temp = new Node;
temp->key = k;
temp->left = temp->right = NULL;
return temp;
}
// Finds the path from root node to given root of the tree,
// Stores the path in a vector path[], returns true if path
// exists otherwise false
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 n2. 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];
}
// Driver program to test above functions
int main()
{
// Let us create the Binary Tree shown in above diagram.
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
cout << "LCA(4, 5) = " << findLCA(root, 4, 5);
cout << "\nLCA(4, 6) = " << findLCA(root, 4, 6);
cout << "\nLCA(3, 4) = " << findLCA(root, 3, 4);
cout << "\nLCA(2, 4) = " << findLCA(root, 2, 4);
return 0;
} | linear | linear |
/* C++ Program to find LCA of n1 and n2 using one traversal
* of Binary Tree */
#include <bits/stdc++.h>
using namespace std;
// A Binary Tree Node
struct Node {
struct Node *left, *right;
int key;
};
// Utility function to create a new tree Node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
// This function returns pointer to LCA of two given values
// n1 and n2. This function assumes that n1 and n2 are
// present in Binary Tree
struct Node* findLCA(struct Node* root, int n1, int n2)
{
// Base case
if (root == NULL)
return NULL;
// If either n1 or n2 matches with root's key, report
// the presence by returning root (Note that if a key is
// ancestor of other, then the ancestor key becomes LCA
if (root->key == n1 || root->key == n2)
return root;
// Look for keys in left and right subtrees
Node* left_lca = findLCA(root->left, n1, n2);
Node* right_lca = findLCA(root->right, n1, n2);
// If both of the above calls return Non-NULL, then one
// key is present in once subtree and other is present
// in other, So this node is the LCA
if (left_lca && right_lca)
return root;
// Otherwise check if left subtree or right subtree is
// LCA
return (left_lca != NULL) ? left_lca : right_lca;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree given in the above example
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
cout << "LCA(4, 5) = " << findLCA(root, 4, 5)->key;
cout << "\nLCA(4, 6) = " << findLCA(root, 4, 6)->key;
cout << "\nLCA(3, 4) = " << findLCA(root, 3, 4)->key;
cout << "\nLCA(2, 4) = " << findLCA(root, 2, 4)->key;
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129) | logn | linear |
/* C++ program to find LCA of n1 and n2 using one traversal
of Binary Tree. It handles all cases even when n1 or n2
is not there in Binary Tree */
#include <iostream>
using namespace std;
// A Binary Tree Node
struct Node {
struct Node *left, *right;
int key;
};
// Utility function to create a new tree Node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
// This function returns pointer to LCA of two given
// valuesn1 and n2.
struct Node* findLCAUtil(struct Node* root, int n1, int n2)
{
// Base case
if (root == NULL)
return NULL;
// If either n1 or n2 matches with root's key, report
// the presence by returning root
if (root->key == n1 || root->key == n2)
return root;
// Look for keys in left and right subtrees
Node* left_lca = findLCAUtil(root->left, n1, n2);
Node* right_lca = findLCAUtil(root->right, n1, n2);
// If both of the above calls return Non-NULL nodes,
// then one key is present in once subtree and other is
// present in other, So this node is the LCA
if (left_lca and right_lca)
return root;
// Otherwise check if left subtree or right subtree is
// LCA
return (left_lca != NULL) ? left_lca : right_lca;
}
// Returns true if key k is present in tree rooted with root
bool find(Node* root, int k)
{
// Base Case
if (root == NULL)
return false;
// If key is present at root, or in left subtree or
// right subtree, return true;
if (root->key == k || find(root->left, k)
|| find(root->right, k))
return true;
// Else return false
return false;
}
// This function returns LCA of n1 and n2 only if both n1
// and n2 are present in tree, otherwise returns NULL;
Node* findLCA(Node* root, int n1, int n2)
{
// Return LCA only if both n1 and n2 are present in tree
if (find(root, n1) and find(root, n2))
return findLCAUtil(root, n1, n2);
// Else return NULL
return NULL;
}
// Driver program to test above functions
int main()
{
// Let us create a binary tree given in the above
// example
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
Node* lca = findLCA(root, 4, 5);
if (lca != NULL)
cout << "LCA(4, 5) = " << lca->key;
else
cout << "Keys are not present ";
lca = findLCA(root, 4, 10);
if (lca != NULL)
cout << "\nLCA(4, 10) = " << lca->key;
else
cout << "\nKeys are not present ";
return 0;
}
// This code is contributed by Kshitij Dwivedi
// (kshitijdwivedi28) | logn | linear |
// C++ program to find maximum difference between node
// and its ancestor
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has key, pointer to left
child and a pointer to right child */
struct Node {
int key;
struct Node *left, *right;
};
/* To create a newNode of tree and return pointer */
struct Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
/* Recursive function to calculate maximum ancestor-node
difference in binary tree. It updates value at 'res'
to store the result. The returned value of this function
is minimum value in subtree rooted with 't' */
int maxDiffUtil(Node* t, int* res)
{
/* Returning Maximum int value if node is not
there (one child case) */
if (t == NULL)
return INT_MAX;
/* If leaf node then just return node's value */
if (t->left == NULL && t->right == NULL)
return t->key;
/* Recursively calling left and right subtree
for minimum value */
int val = min(maxDiffUtil(t->left, res),
maxDiffUtil(t->right, res));
/* Updating res if (node value - minimum value
from subtree) is bigger than res */
*res = max(*res, t->key - val);
/* Returning minimum value got so far */
return min(val, t->key);
}
/* This function mainly calls maxDiffUtil() */
int maxDiff(Node* root)
{
// Initialising result with minimum int value
int res = INT_MIN;
maxDiffUtil(root, &res);
return res;
}
/* Helper function to print inorder traversal of
binary tree */
void inorder(Node* root)
{
if (root) {
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
// Driver program to test above functions
int main()
{
// Making above given diagram's binary tree
Node* root;
root = newNode(8);
root->left = newNode(3);
root->left->left = newNode(1);
root->left->right = newNode(6);
root->left->right->left = newNode(4);
root->left->right->right = newNode(7);
root->right = newNode(10);
root->right->right = newNode(14);
root->right->right->left = newNode(13);
cout << maxDiff(root);
} | linear | linear |
// C++ program to count number of ways to color
// a N node skewed tree with k colors such that
// parent and children have different colors.
#include <bits/stdc++.h>
using namespace std;
// fast_way is recursive
// method to calculate power
int fastPow(int N, int K)
{
if (K == 0)
return 1;
int temp = fastPow(N, K / 2);
if (K % 2 == 0)
return temp * temp;
else
return N * temp * temp;
}
int countWays(int N, int K)
{
return K * fastPow(K - 1, N - 1);
}
// driver program
int main()
{
int N = 3, K = 3;
cout << countWays(N, K);
return 0;
} | constant | logn |
// C++ program to print size of tree in iterative
#include<iostream>
#include<queue>
using namespace std;
struct Node
{
int data;
Node *left, *right;
};
// A utility function to
// create a new Binary Tree Node
Node *newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// return size of tree
int sizeoftree(Node *root)
{
// if tree is empty it will
// return 0
if(root == NULL)
return 0;
// Using level order Traversal.
queue<Node *> q;
int count = 1;
q.push(root);
while(!q.empty())
{
Node *temp = q.front();
if(temp->left)
{
// Enqueue left child
q.push(temp->left);
// Increment count
count++;
}
if(temp->right)
{
// Enqueue right child
q.push(temp->right);
// Increment count
count++;
}
q.pop();
}
return count;
}
// Driver Code
int main()
{
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "Size of the tree is " <<
sizeoftree(root) << endl;
return 0;
}
// This code is contributed by SHAKEELMOHAMMAD | np | linear |
// C++ program to find height of tree
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class node {
public:
int data;
node* left;
node* right;
};
/* Compute the "maxDepth" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int maxDepth(node* node)
{
if (node == NULL)
return 0;
else {
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
/* use the larger one */
if (lDepth > rDepth)
return (lDepth + 1);
else
return (rDepth + 1);
}
}
/* 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 = NULL;
Node->right = NULL;
return (Node);
}
// Driver code
int main()
{
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "Height of tree is " << maxDepth(root);
return 0;
}
// This code is contributed by Amit Srivastav | linear | linear |
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
// A Tree node
struct Node {
int key;
struct Node *left, *right;
};
// Utility function to create a new node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
/*Function to find the height(depth) of the tree*/
int height(struct Node* root)
{
// Initialising a variable to count the
// height of tree
int depth = 0;
queue<Node*> q;
// Pushing first level element along with NULL
q.push(root);
q.push(NULL);
while (!q.empty()) {
Node* temp = q.front();
q.pop();
// When NULL encountered, increment the value
if (temp == NULL) {
depth++;
}
// If NULL not encountered, keep moving
if (temp != NULL) {
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
}
// If queue still have elements left,
// push NULL again to the queue.
else if (!q.empty()) {
q.push(NULL);
}
}
return depth;
}
// Driver program
int main()
{
// Let us create Binary Tree shown in above example
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "Height(Depth) of tree is: " << height(root);
} | linear | linear |
// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
// A Tree node
struct Node {
int key;
struct Node *left, *right;
};
// Utility function to create a new node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
/*Function to find the height(depth) of the tree*/
int height(Node* root)
{
// Initialising a variable to count the
// height of tree
queue<Node*> q;
q.push(root);
int height = 0;
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
Node* temp = q.front();
q.pop();
if (temp->left != NULL) {
q.push(temp->left);
}
if (temp->right != NULL) {
q.push(temp->right);
}
}
height++;
}
return height;
}
// Driver program
int main()
{
// Let us create Binary Tree shown in above example
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "Height(Depth) of tree is: " << height(root);
}
// This code is contributed by Abhijeet Kumar(abhijeet19403) | linear | linear |
#include <iostream>
#include <queue>
using namespace std;
// This approach counts the number of nodes from root to the
// leaf to calculate the height of the tree.
// Defining the structure of a Node.
class Node {
public:
int data;
Node* left;
Node* right;
};
// Helper function to create a newnode.
// Input: Data for the newnode.
// Return: Address of the newly created node.
Node* createNode(int data)
{
Node* newnode = new Node();
newnode->data = data;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
// Function to calculate the height of given Binary Tree.
// Input: Address of the root node of Binary Tree.
// Return: Height of Binary Tree as a integer. This includes
// the number of nodes from root to the leaf.
int calculateHeight(Node* root)
{
queue<Node*> nodesInLevel;
int height = 0;
int nodeCount = 0; // Calculate number of nodes in a level.
Node* currentNode; // Pointer to store the address of a
// node in the current level.
if (root == NULL) {
return 0;
}
nodesInLevel.push(root);
while (!nodesInLevel.empty()) {
// This while loop runs for every level and
// increases the height by 1 in each iteration. If
// the queue is empty then it implies that the last
// level of tree has been parsed.
height++;
// Create another while loop which will insert all
// the child nodes of the current level in the
// queue.
nodeCount = nodesInLevel.size();
while (nodeCount--) {
currentNode = nodesInLevel.front();
// Check if the current nodes has left child and
// insert it in the queue.
if (currentNode->left != NULL) {
nodesInLevel.push(currentNode->left);
}
// Check if the current nodes has right child
// and insert it in the queue.
if (currentNode->right != NULL) {
nodesInLevel.push(currentNode->right);
}
// Once the children of the current node are
// inserted. Delete the current node.
nodesInLevel.pop();
}
}
return height;
}
// Driver Function.
int main()
{
// Creating a binary tree.
Node* root = NULL;
root = createNode(1);
root->left = createNode(2);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right = createNode(3);
cout << "The height of the binary tree using iterative "
"method is: " << calculateHeight(root) << ".";
return 0;
} | linear | linear |
// CPP program to find height of complete
// binary tree from total nodes.
#include <bits/stdc++.h>
using namespace std;
int height(int N)
{
return floor(log2(N));
}
// driver node
int main()
{
int N = 2;
cout << height(N);
return 0;
} | constant | constant |
/* Program to find height of the tree considering
only even level leaves. */
#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;
struct Node* right;
};
int heightOfTreeUtil(Node* root, bool isEven)
{
// Base Case
if (!root)
return 0;
if (!root->left && !root->right) {
if (isEven)
return 1;
else
return 0;
}
/*left stores the result of left subtree,
and right stores the result of right subtree*/
int left = heightOfTreeUtil(root->left, !isEven);
int right = heightOfTreeUtil(root->right, !isEven);
/*If both left and right returns 0, it means
there is no valid path till leaf node*/
if (left == 0 && right == 0)
return 0;
return (1 + max(left, right));
}
/* 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);
}
int heightOfTree(Node* root)
{
return heightOfTreeUtil(root, false);
}
/* Driver program to test above functions*/
int main()
{
// Let us create binary tree shown in above diagram
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->right->left = newNode(6);
cout << "Height of tree is " << heightOfTree(root);
return 0;
} | linear | linear |
/* CPP program to check if
a tree is height-balanced or not */
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data,
pointer to left child and
a pointer to right child */
class Node {
public:
int data;
Node* left;
Node* right;
Node(int d)
{
int data = d;
left = right = NULL;
}
};
// Function to calculate the height of a tree
int height(Node* node)
{
// base case tree is empty
if (node == NULL)
return 0;
// If tree is not empty then
// height = 1 + max of left height
// and right heights
return 1 + max(height(node->left), height(node->right));
}
// Returns true if binary tree
// with root as root is height-balanced
bool isBalanced(Node* root)
{
// for height of left subtree
int lh;
// for height of right subtree
int rh;
// If tree is empty then return true
if (root == NULL)
return 1;
// Get the height of left and right sub trees
lh = height(root->left);
rh = height(root->right);
if (abs(lh - rh) <= 1 && isBalanced(root->left)
&& isBalanced(root->right))
return 1;
// If we reach here then tree is not height-balanced
return 0;
}
// Driver code
int main()
{
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->left->left->left = new Node(8);
if (isBalanced(root))
cout << "Tree is balanced";
else
cout << "Tree is not balanced";
return 0;
}
// This code is contributed by rathbhupendra | linear | quadratic |
// 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);
// returns max of two integers
int max(int a, int b) { return (a > b) ? a : b; }
// function to Compute height of a tree.
int height(struct node* node);
// Function to get diameter of a binary tree
int diameter(struct node* tree)
{
// base case where tree is empty
if (tree == NULL)
return 0;
// get the height of left and right sub-trees
int lheight = height(tree->left);
int rheight = height(tree->right);
// get the diameter of left and right sub-trees
int ldiameter = diameter(tree->left);
int rdiameter = diameter(tree->right);
// Return max of following three
// 1) Diameter of left subtree
// 2) Diameter of right subtree
// 3) Height of left subtree + height of right subtree +
// 1
return max(lheight + rheight + 1,
max(ldiameter, rdiameter));
}
// UTILITY FUNCTIONS TO TEST diameter() FUNCTION
// The function Compute the "height" of a tree. Height is
// the number f nodes along the longest path from the root
// node down to the farthest leaf node.
int height(struct node* node)
{
// base case tree is empty
if (node == NULL)
return 0;
// If tree is not empty then height = 1 + max of left
// height and right heights
return 1 + max(height(node->left), height(node->right));
}
// 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);
// Function Call
cout << "Diameter of the given binary tree is "
<< diameter(root);
return 0;
}
// This code is contributed by shivanisinghss2110 | linear | quadratic |
// 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. | linear | linear |
// Simple C++ program to find diameter
// of a binary tree.
#include <bits/stdc++.h>
using namespace std;
/* Tree node structure used in the program */
struct Node {
int data;
Node* left, *right;
};
/* Function to find height of a tree */
int height(Node* root, int& ans)
{
if (root == NULL)
return 0;
int left_height = height(root->left, ans);
int right_height = height(root->right, ans);
// update the answer, because diameter of a
// tree is nothing but maximum value of
// (left_height + right_height + 1) for each node
ans = max(ans, 1 + left_height + right_height);
return 1 + max(left_height, right_height);
}
/* Computes the diameter of binary tree with given root. */
int diameter(Node* root)
{
if (root == NULL)
return 0;
int ans = INT_MIN; // This will store the final answer
height(root, ans);
return ans;
}
struct Node* newNode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Driver code
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Diameter is %d\n", diameter(root));
return 0;
} | logn | linear |
// CPP program to find deepest right leaf
// node of binary tree
#include <bits/stdc++.h>
using namespace std;
// tree node
struct Node {
int data;
Node *left, *right;
};
// returns a new tree Node
Node* newNode(int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// return the deepest right leaf node
// of binary tree
Node* getDeepestRightLeafNode(Node* root)
{
if (!root)
return NULL;
// create a queue for level order traversal
queue<Node*> q;
q.push(root);
Node* result = NULL;
// traverse until the queue is empty
while (!q.empty()) {
Node* temp = q.front();
q.pop();
if (temp->left) {
q.push(temp->left);
}
// Since we go level by level, the last
// stored right leaf node is deepest one
if (temp->right) {
q.push(temp->right);
if (!temp->right->left && !temp->right->right)
result = temp->right;
}
}
return result;
}
// driver program
int main()
{
// construct a tree
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->right = newNode(7);
root->right->right->right = newNode(8);
root->right->left->right->left = newNode(9);
root->right->right->right->right = newNode(10);
Node* result = getDeepestRightLeafNode(root);
if (result)
cout << "Deepest Right Leaf Node :: "
<< result->data << endl;
else
cout << "No result, right leaf not found\n";
return 0;
} | linear | linear |
// A C++ program to find value of the deepest node
// in a given binary tree
#include <bits/stdc++.h>
using namespace std;
// A tree node
struct Node
{
int data;
struct Node *left, *right;
};
// Utility function to create a new node
Node *newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// maxLevel : keeps track of maximum level seen so far.
// res : Value of deepest node so far.
// level : Level of root
void find(Node *root, int level, int &maxLevel, int &res)
{
if (root != NULL)
{
find(root->left, ++level, maxLevel, res);
// Update level and rescue
if (level > maxLevel)
{
res = root->data;
maxLevel = level;
}
find(root->right, level, maxLevel, res);
}
}
// Returns value of deepest node
int deepestNode(Node *root)
{
// Initialize result and max level
int res = -1;
int maxLevel = -1;
// Updates value "res" and "maxLevel"
// Note that res and maxLen are passed
// by reference.
find(root, 0, maxLevel, res);
return res;
}
// Driver program
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->right = newNode(7);
root->right->right->right = newNode(8);
root->right->left->right->left = newNode(9);
cout << deepestNode(root);
return 0;
} | linear | linear |
// A C++ program to find value of the
// deepest node in a given binary tree
#include <bits/stdc++.h>
using namespace std;
// A tree node with constructor
class Node
{
public:
int data;
Node *left, *right;
// constructor
Node(int key)
{
data = key;
left = NULL;
right = NULL;
}
};
// Function to return the deepest node
Node* deepestNode(Node* root)
{
Node* tmp = NULL;
if (root == NULL)
return NULL;
// Creating a Queue
queue<Node*> q;
q.push(root);
// Iterates until queue become empty
while (q.size() > 0)
{
tmp = q.front();
q.pop();
if (tmp->left != NULL)
q.push(tmp->left);
if (tmp->right != NULL)
q.push(tmp->right);
}
return tmp;
}
int main()
{
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->right->left = new Node(5);
root->right->right = new Node(6);
root->right->left->right = new Node(7);
root->right->right->right = new Node(8);
root->right->left->right->left = new Node(9);
Node* deepNode = deepestNode(root);
cout << (deepNode->data);
return 0;
} | linear | linear |
// CPP program to find deepest left leaf
// node of binary tree
#include <bits/stdc++.h>
using namespace std;
// tree node
struct Node {
int data;
Node *left, *right;
};
// returns a new tree Node
Node* newNode(int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// return the deepest left leaf node
// of binary tree
Node* getDeepestLeftLeafNode(Node* root)
{
if (!root)
return NULL;
// create a queue for level order traversal
queue<Node*> q;
q.push(root);
Node* result = NULL;
// traverse until the queue is empty
while (!q.empty()) {
Node* temp = q.front();
q.pop();
// Since we go level by level, the last
// stored left leaf node is deepest one,
if (temp->left) {
q.push(temp->left);
if (!temp->left->left && !temp->left->right)
result = temp->left;
}
if (temp->right)
q.push(temp->right);
}
return result;
}
// driver program
int main()
{
// construct a tree
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->right = newNode(7);
root->right->right->right = newNode(8);
root->right->left->right->left = newNode(9);
root->right->right->right->right = newNode(10);
Node* result = getDeepestLeftLeafNode(root);
if (result)
cout << "Deepest Left Leaf Node :: "
<< result->data << endl;
else
cout << "No result, left leaf not found\n";
return 0;
} | linear | linear |
// C++ program to calculate width of 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 */
class node {
public:
int data;
node* left;
node* right;
node (int d){
this->data = d;
this->left = this->right = NULL;
}
};
/*Function prototypes*/
int getWidth(node* root, int level);
int height(node* node);
/* 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;
/* Get width of each level and compare
the width with maximum width so far */
for (i = 1; i <= h; i++) {
width = getWidth(root, i);
if (width > maxWidth)
maxWidth = width;
}
return maxWidth;
}
/* Get width of a given level */
int getWidth(node* root, int level)
{
if (root == NULL)
return 0;
if (level == 1)
return 1;
else if (level > 1)
return getWidth(root->left, level - 1)
+ getWidth(root->right, level - 1);
}
/* UTILITY FUNCTIONS */
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(node* node)
{
if (node == NULL)
return 0;
else {
/* compute the height of each subtree */
int lHeight = height(node->left);
int rHeight = height(node->right);
/* use the larger one */
return (lHeight > rHeight) ? (lHeight + 1)
: (rHeight + 1);
}
}
/* Driver code*/
int main()
{
node* root = new node(1);
root->left = new node(2);
root->right = new node(3);
root->left->left = new node(4);
root->left->right = new node(5);
root->right->right = new node(8);
root->right->right->left = new node(6);
root->right->right->right = new node(7);
/*
Constructed binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
*/
// Function call
cout << "Maximum width is " << getMaxWidth(root)
<< endl;
return 0;
}
// This code is contributed by rathbhupendra | constant | quadratic |
// A queue based C++ program to find maximum width
// 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;
struct Node* right;
Node(int d)
{
this->data = d;
this->left = this->right = NULL;
}
};
// Function to find the maximum width of the tree
// using level order traversal
int maxWidth(struct Node* root)
{
// Base case
if (root == NULL)
return 0;
// Initialize result
int result = 0;
// Do Level order traversal keeping track of number
// of nodes at every level.
queue<Node*> q;
q.push(root);
while (!q.empty()) {
// Get the size of queue when the level order
// traversal for one level finishes
int count = q.size();
// Update the maximum node count value
result = max(count, result);
// Iterate for all the nodes in the queue currently
while (count--) {
// Dequeue an node from queue
Node* temp = q.front();
q.pop();
// Enqueue left and right children of
// dequeued node
if (temp->left != NULL)
q.push(temp->left);
if (temp->right != NULL)
q.push(temp->right);
}
}
return result;
}
// Driver code
int main()
{
struct Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->right = new Node(8);
root->right->right->left = new Node(6);
root->right->right->right = new Node(7);
/* Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7 */
// Function call
cout << "Maximum width is " << maxWidth(root) << endl;
return 0;
}
// This code is contributed by Nikhil Kumar
// Singh(nickzuck_007) | np | linear |
// C++ program to calculate width of 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 */
class node {
public:
int data;
node* left;
node* right;
node(int d)
{
this->data = d;
this->left = this->right = NULL;
}
};
// A utility function to get
// height of a binary tree
int height(node* node);
// A utility function that returns
// maximum value in arr[] of size n
int getMax(int arr[], int n);
// A function that fills count array
// with count of nodes at every
// level of given binary tree
void getMaxWidthRecur(node* root, int count[], int level);
/* Function to get the maximum
width of a binary tree*/
int getMaxWidth(node* root)
{
int width;
int h = height(root);
// Create an array that will
// store count of nodes at each level
int* count = new int[h];
int level = 0;
// Fill the count array using preorder traversal
getMaxWidthRecur(root, count, level);
// Return the maximum value from count array
return getMax(count, h);
}
// A function that fills count array
// with count of nodes at every
// level of given binary tree
void getMaxWidthRecur(node* root,
int count[], int level)
{
if (root) {
count[level]++;
getMaxWidthRecur(root->left, count, level + 1);
getMaxWidthRecur(root->right, count, level + 1);
}
}
/* UTILITY FUNCTIONS */
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(node* node)
{
if (node == NULL)
return 0;
else {
/* compute the height of each subtree */
int lHeight = height(node->left);
int rHeight = height(node->right);
/* use the larger one */
return (lHeight > rHeight) ? (lHeight + 1)
: (rHeight + 1);
}
}
// Return the maximum value from count array
int getMax(int arr[], int n)
{
int max = arr[0];
int i;
for (i = 0; i < n; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}
/* Driver code*/
int main()
{
node* root = new node(1);
root->left = new node(2);
root->right = new node(3);
root->left->left = new node(4);
root->left->right = new node(5);
root->right->right = new node(8);
root->right->right->left = new node(6);
root->right->right->right = new node(7);
cout << "Maximum width is " << getMaxWidth(root)
<< endl;
return 0;
}
// This is code is contributed by rathbhupendra | logn | linear |
// CPP program to print vertical width
// of a tree
#include <bits/stdc++.h>
using namespace std;
// A Binary Tree Node
struct Node {
int data;
struct Node *left, *right;
};
// get vertical width
void lengthUtil(Node* root, int& maximum, int& minimum,
int curr = 0)
{
if (root == NULL)
return;
// traverse left
lengthUtil(root->left, maximum, minimum, curr - 1);
// if curr is decrease then get
// value in minimum
if (minimum > curr)
minimum = curr;
// if curr is increase then get
// value in maximum
if (maximum < curr)
maximum = curr;
// traverse right
lengthUtil(root->right, maximum, minimum, curr + 1);
}
int getLength(Node* root)
{
int maximum = 0, minimum = 0;
lengthUtil(root, maximum, minimum, 0);
// 1 is added to include root in the width
return (abs(minimum) + maximum) + 1;
}
// Utility function to create a new tree node
Node* newNode(int data)
{
Node* curr = new Node;
curr->data = data;
curr->left = curr->right = NULL;
return curr;
}
// Driver program to test above functions
int main()
{
Node* root = newNode(7);
root->left = newNode(6);
root->right = newNode(5);
root->left->left = newNode(4);
root->left->right = newNode(3);
root->right->left = newNode(2);
root->right->right = newNode(1);
cout << getLength(root) << "\n";
return 0;
} | logn | linear |
// C++ program to find Vertical Height of a tree
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* left;
struct Node* right;
Node(int x)
{
data = x;
left = right = NULL;
}
};
int verticalWidth(Node* root)
{
// Code here
if (root == NULL)
return 0;
int maxLevel = 0, minLevel = 0;
queue<pair<Node*, int> > q;
q.push({ root, 0 }); // we take root as 0
// Level order traversal code
while (q.empty() != true) {
Node* cur = q.front().first;
int count = q.front().second;
q.pop();
if (cur->left) {
minLevel = min(minLevel,
count - 1); // as we go left,
// level is decreased
q.push({ cur->left, count - 1 });
}
if (cur->right) {
maxLevel = max(maxLevel,
count + 1); // as we go right,
// level is increased
q.push({ cur->right, count + 1 });
}
}
return maxLevel + abs(minLevel)
+ 1; // +1 for the root node, we gave it a value
// of zero
}
int main()
{
// making the tree
Node* root = new Node(7);
root->left = new Node(6);
root->right = new Node(5);
root->left->left = new Node(4);
root->left->right = new Node(3);
root->right->left = new Node(2);
root->right->right = new Node(1);
cout << "Vertical width is : " << verticalWidth(root)
<< endl;
return 0;
}
// code contributed by Anshit Bansal | linear | linear |
// CPP code to find vertical
// width of a binary tree
#include <bits/stdc++.h>
using namespace std;
// Tree class
class Node
{
public :
int data;
Node *left, *right;
// Constructor
Node(int data_new)
{
data = data_new;
left = right = NULL;
}
};
// Function to fill hd in set.
void fillSet(Node* root, unordered_set<int>& s,
int hd)
{
if (!root)
return;
fillSet(root->left, s, hd - 1);
s.insert(hd);
fillSet(root->right, s, hd + 1);
}
int verticalWidth(Node* root)
{
unordered_set<int> s;
// Third parameter is horizontal
// distance
fillSet(root, s, 0);
return s.size();
}
int main()
{
Node* root = NULL;
// Creating the above tree
root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
root->right->left->right = new Node(8);
root->right->right->right = new Node(9);
cout << verticalWidth(root) << "\n";
return 0;
} | linear | linear |
// CPP program to determine whether
// vertical level l of binary tree
// is sorted or not.
#include <bits/stdc++.h>
using namespace std;
// Structure of a tree node.
struct Node {
int key;
Node *left, *right;
};
// Function to create new tree node.
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
// Helper function to determine if
// vertical level l of given binary
// tree is sorted or not.
bool isSorted(Node* root, int level)
{
// If root is null, then the answer is an
// empty subset and an empty subset is
// always considered to be sorted.
if (root == NULL)
return true;
// Variable to store previous
// value in vertical level l.
int prevVal = INT_MIN;
// Variable to store current level
// while traversing tree vertically.
int currLevel;
// Variable to store current node
// while traversing tree vertically.
Node* currNode;
// Declare queue to do vertical order
// traversal. A pair is used as element
// of queue. The first element in pair
// represents the node and the second
// element represents vertical level
// of that node.
queue<pair<Node*, int> > q;
// Insert root in queue. Vertical level
// of root is 0.
q.push(make_pair(root, 0));
// Do vertical order traversal until
// all the nodes are not visited.
while (!q.empty()) {
currNode = q.front().first;
currLevel = q.front().second;
q.pop();
// Check if level of node extracted from
// queue is required level or not. If it
// is the required level then check if
// previous value in that level is less
// than or equal to value of node.
if (currLevel == level) {
if (prevVal <= currNode->key)
prevVal = currNode->key;
else
return false;
}
// If left child is not NULL then push it
// in queue with level reduced by 1.
if (currNode->left)
q.push(make_pair(currNode->left, currLevel - 1));
// If right child is not NULL then push it
// in queue with level increased by 1.
if (currNode->right)
q.push(make_pair(currNode->right, currLevel + 1));
}
// If the level asked is not present in the
// given binary tree, that means that level
// will contain an empty subset. Therefore answer
// will be true.
return true;
}
// Driver program
int main()
{
/*
1
/ \
2 5
/ \
7 4
/
6
*/
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(7);
root->left->right = newNode(4);
root->left->right->left = newNode(6);
int level = -1;
if (isSorted(root, level) == true)
cout << "Yes";
else
cout << "No";
return 0;
} | linear | linear |
// CPP program to determine whether
// binary tree is level sorted or not.
#include <bits/stdc++.h>
using namespace std;
// Structure of a tree node.
struct Node {
int key;
Node *left, *right;
};
// Function to create new tree node.
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
// Function to determine if
// given binary tree is level sorted
// or not.
int isSorted(Node* root)
{
// to store maximum value of previous
// level.
int prevMax = INT_MIN;
// to store minimum value of current
// level.
int minval;
// to store maximum value of current
// level.
int maxval;
// to store number of nodes in current
// level.
int levelSize;
// queue to perform level order traversal.
queue<Node*> q;
q.push(root);
while (!q.empty()) {
// find number of nodes in current
// level.
levelSize = q.size();
minval = INT_MAX;
maxval = INT_MIN;
// traverse current level and find
// minimum and maximum value of
// this level.
while (levelSize > 0) {
root = q.front();
q.pop();
levelSize--;
minval = min(minval, root->key);
maxval = max(maxval, root->key);
if (root->left)
q.push(root->left);
if (root->right)
q.push(root->right);
}
// if minimum value of this level
// is not greater than maximum
// value of previous level then
// given tree is not level sorted.
if (minval <= prevMax)
return 0;
// maximum value of this level is
// previous maximum value for
// next level.
prevMax = maxval;
}
return 1;
}
// Driver program
int main()
{
/*
1
/
4
\
6
/ \
8 9
/ \
12 10
*/
Node* root = newNode(1);
root->left = newNode(4);
root->left->right = newNode(6);
root->left->right->left = newNode(8);
root->left->right->right = newNode(9);
root->left->right->left->left = newNode(12);
root->left->right->right->right = newNode(10);
if (isSorted(root))
cout << "Sorted";
else
cout << "Not sorted";
return 0;
} | linear | linear |
// C++ Program to print Bottom View of Binary Tree
#include<bits/stdc++.h>
using namespace std;
// Tree node class
struct Node
{
int data; //data of the node
int hd; //horizontal distance of the node
Node *left, *right; //left and right references
// Constructor of tree node
Node(int key)
{
data = key;
hd = INT_MAX;
left = right = NULL;
}
};
// Method that prints the bottom view.
void bottomView(Node *root)
{
if (root == NULL)
return;
// Initialize a variable 'hd' with 0
// for the root element.
int hd = 0;
// TreeMap which stores key value pair
// sorted on key value
map<int, int> m;
// Queue to store tree nodes in level
// order traversal
queue<Node *> q;
// Assign initialized horizontal distance
// value to root node and add it to the queue.
root->hd = hd;
q.push(root); // In STL, push() is used enqueue an item
// Loop until the queue is empty (standard
// level order loop)
while (!q.empty())
{
Node *temp = q.front();
q.pop(); // In STL, pop() is used dequeue an item
// Extract the horizontal distance value
// from the dequeued tree node.
hd = temp->hd;
// Put the dequeued tree node to TreeMap
// having key as horizontal distance. Every
// time we find a node having same horizontal
// distance we need to replace the data in
// the map.
m[hd] = temp->data;
// If the dequeued node has a left child, add
// it to the queue with a horizontal distance hd-1.
if (temp->left != NULL)
{
temp->left->hd = hd-1;
q.push(temp->left);
}
// If the dequeued node has a right child, add
// it to the queue with a horizontal distance
// hd+1.
if (temp->right != NULL)
{
temp->right->hd = hd+1;
q.push(temp->right);
}
}
// Traverse the map elements using the iterator.
for (auto i = m.begin(); i != m.end(); ++i)
cout << i->second << " ";
}
// Driver Code
int main()
{
Node *root = new Node(20);
root->left = new Node(8);
root->right = new Node(22);
root->left->left = new Node(5);
root->left->right = new Node(3);
root->right->left = new Node(4);
root->right->right = new Node(25);
root->left->right->left = new Node(10);
root->left->right->right = new Node(14);
cout << "Bottom view of the given binary tree :\n";
bottomView(root);
return 0;
} | linear | nlogn |
// C++ Program to print Bottom View of Binary Tree
#include <bits/stdc++.h>
#include <map>
using namespace std;
// Tree node class
struct Node
{
// data of the node
int data;
// horizontal distance of the node
int hd;
//left and right references
Node * left, * right;
// Constructor of tree node
Node(int key)
{
data = key;
hd = INT_MAX;
left = right = NULL;
}
};
void printBottomViewUtil(Node * root, int curr, int hd, map <int, pair <int, int>> & m)
{
// Base case
if (root == NULL)
return;
// If node for a particular
// horizontal distance is not
// present, add to the map.
if (m.find(hd) == m.end())
{
m[hd] = make_pair(root -> data, curr);
}
// Compare height for already
// present node at similar horizontal
// distance
else
{
pair < int, int > p = m[hd];
if (p.second <= curr)
{
m[hd].second = curr;
m[hd].first = root -> data;
}
}
// Recur for left subtree
printBottomViewUtil(root -> left, curr + 1, hd - 1, m);
// Recur for right subtree
printBottomViewUtil(root -> right, curr + 1, hd + 1, m);
}
void printBottomView(Node * root)
{
// Map to store Horizontal Distance,
// Height and Data.
map < int, pair < int, int > > m;
printBottomViewUtil(root, 0, 0, m);
// Prints the values stored by printBottomViewUtil()
map < int, pair < int, int > > ::iterator it;
for (it = m.begin(); it != m.end(); ++it)
{
pair < int, int > p = it -> second;
cout << p.first << " ";
}
}
int main()
{
Node * root = new Node(20);
root -> left = new Node(8);
root -> right = new Node(22);
root -> left -> left = new Node(5);
root -> left -> right = new Node(3);
root -> right -> left = new Node(4);
root -> right -> right = new Node(25);
root -> left -> right -> left = new Node(10);
root -> left -> right -> right = new Node(14);
cout << "Bottom view of the given binary tree :\n";
printBottomView(root);
return 0;
} | linear | nlogn |
#include <bits/stdc++.h>
using namespace std;
// Tree node class
struct Node
{
// data of the node
int data;
// horizontal distance of the node
int hd;
//left and right references
Node * left, * right;
// Constructor of tree node
Node(int key)
{
data = key;
hd = INT_MAX;
left = right = NULL;
}
};
void printBottomView(Node * root)
{
if(!root) return ;//if root is NULL
unordered_map<int,int> hash; // <vertical_index , root->data>
int leftmost = 0; // to store the leftmost index so that we move from left to right
queue<pair<Node*,int>> q; // pair<Node*,vertical Index> for level order traversal.
q.push({root,0}); // push the root and 0 vertial index
while(!q.empty()){
auto top = q.front(); // store q.front() in top variable
q.pop();
Node *temp = top.first; // store the Node in temp for left and right nodes
int ind = top.second; // store the vertical index of current node
hash[ind] = temp->data; // store the latest vertical_index(key) -> root->data(value)
leftmost = min(ind,leftmost); // have the leftmost vertical index
if(temp->left){ q.push({temp->left,ind-1});}// check if any node of left then go in negative direction
if(temp->right){ q.push({temp->right,ind+1});} //check if any node of left then go in positive direction
}
//teverse each value in hash from leftmost to positive side till key is available
while(hash.find(leftmost)!=hash.end()){ cout<<hash[leftmost++]<<" "; }
}
int main()
{
Node * root = new Node(20);
root -> left = new Node(8);
root -> right = new Node(22);
root -> left -> left = new Node(5);
root -> left -> right = new Node(3);
root -> right -> left = new Node(4);
root -> right -> right = new Node(25);
root -> left -> right -> left = new Node(10);
root -> left -> right -> right = new Node(14);
cout << "Bottom view of the given binary tree :\n";
printBottomView(root);
return 0;
} | linear | linear |
// C++ program to count half nodes in 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 get the count of half Nodes in
// a binary tree
unsigned int gethalfCount(struct Node* node)
{
// If tree is empty
if (!node)
return 0;
int count = 0; // Initialize count of half nodes
// Do level order traversal starting from root
queue<Node *> q;
q.push(node);
while (!q.empty())
{
struct Node *temp = q.front();
q.pop();
if (!temp->left && temp->right ||
temp->left && !temp->right)
count++;
if (temp->left != NULL)
q.push(temp->left);
if (temp->right != NULL)
q.push(temp->right);
}
return count;
}
/* 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 = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Driver program
int main(void)
{
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree shown in
above example */
struct Node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
cout << gethalfCount(root);
return 0;
} | linear | linear |
// C++ program to count half nodes in 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 get the count of half Nodes in
// a binary tree
unsigned int gethalfCount(struct Node* root)
{
if (root == NULL)
return 0;
int res = 0;
if ((root->left == NULL && root->right != NULL) ||
(root->left != NULL && root->right == NULL))
res++;
res += (gethalfCount(root->left) + gethalfCount(root->right));
return res;
}
/* 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 = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Driver program
int main(void)
{
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree shown in
above example */
struct Node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
cout << gethalfCount(root);
return 0;
} | linear | linear |
// C++ program to count
// full nodes in 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 get the count of full Nodes in
// a binary tree
unsigned int getfullCount(struct Node* node)
{
// If tree is empty
if (!node)
return 0;
queue<Node *> q;
// Do level order traversal starting from root
int count = 0; // Initialize count of full nodes
q.push(node);
while (!q.empty())
{
struct Node *temp = q.front();
q.pop();
if (temp->left && temp->right)
count++;
if (temp->left != NULL)
q.push(temp->left);
if (temp->right != NULL)
q.push(temp->right);
}
return count;
}
/* 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 = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Driver program
int main(void)
{
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
struct Node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
cout << getfullCount(root);
return 0;
} | linear | linear |
// C++ program to count full nodes in 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 get the count of full Nodes in
// a binary tree
unsigned int getfullCount(struct Node* root)
{
if (root == NULL)
return 0;
int res = 0;
if (root->left && root->right)
res++;
res += (getfullCount(root->left) +
getfullCount(root->right));
return res;
}
/* 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 = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Driver program
int main(void)
{
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
struct Node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
cout << getfullCount(root);
return 0;
} | linear | linear |
// Connect nodes at same level using level order
// traversal.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* left, *right, *nextRight;
};
// Sets nextRight of all nodes of a tree
void connect(struct Node* root)
{
queue<Node*> q;
q.push(root);
// null marker to represent end of current level
q.push(NULL);
// Do Level order of tree using NULL markers
while (!q.empty()) {
Node *p = q.front();
q.pop();
if (p != NULL) {
// next element in queue represents next
// node at current Level
p->nextRight = q.front();
// push left and right children of current
// node
if (p->left)
q.push(p->left);
if (p->right)
q.push(p->right);
}
// if queue is not empty, push NULL to mark
// nodes at this level are visited
else if (!q.empty())
q.push(NULL);
}
}
/* UTILITY FUNCTIONS */
/* 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 = node->right = node->nextRight = NULL;
return (node);
}
/* Driver program to test above functions*/
int main()
{
/* Constructed binary tree is
10
/ \
8 2
/ \
3 90
*/
struct Node* root = newnode(10);
root->left = newnode(8);
root->right = newnode(2);
root->left->left = newnode(3);
root->right->right = newnode(90);
// Populates nextRight pointer in all nodes
connect(root);
// Let us check the values of nextRight pointers
printf("Following are populated nextRight pointers in \n"
"the tree (-1 is printed if there is no nextRight) \n");
printf("nextRight of %d is %d \n", root->data,
root->nextRight ? root->nextRight->data : -1);
printf("nextRight of %d is %d \n", root->left->data,
root->left->nextRight ? root->left->nextRight->data : -1);
printf("nextRight of %d is %d \n", root->right->data,
root->right->nextRight ? root->right->nextRight->data : -1);
printf("nextRight of %d is %d \n", root->left->left->data,
root->left->left->nextRight ? root->left->left->nextRight->data : -1);
printf("nextRight of %d is %d \n", root->right->right->data,
root->right->right->nextRight ? root->right->right->nextRight->data : -1);
return 0;
} | linear | linear |
// Iterative CPP program to connect
// nodes at same level using
// constant extra space
#include<bits/stdc++.h>
#include<bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node* left;
node* right;
node *nextRight;
/* Constructor that allocates a new node with the
given data and NULL left and right pointers. */
node(int data)
{
this->data = data;
this->left = NULL;
this->right = NULL;
this->nextRight = NULL;
}
};
/* This function returns the leftmost
child of nodes at the same level as p.
This function is used to getNExt right
of p's right child If right child of
is NULL then this can also be used for
the left child */
node *getNextRight(node *p)
{
node *temp = p->nextRight;
/* Traverse nodes at p's level
and find and return the first
node's first child */
while (temp != NULL)
{
if (temp->left != NULL)
return temp->left;
if (temp->right != NULL)
return temp->right;
temp = temp->nextRight;
}
// If all the nodes at p's level
// are leaf nodes then return NULL
return NULL;
}
/* Sets nextRight of all nodes
of a tree with root as p */
void connectRecur(node* p)
{
node *temp;
if (!p)
return;
// Set nextRight for root
p->nextRight = NULL;
// set nextRight of all levels one by one
while (p != NULL)
{
node *q = p;
/* Connect all children nodes of p and
children nodes of all other nodes at
same level as p */
while (q != NULL)
{
// Set the nextRight pointer
// for p's left child
if (q->left)
{
// If q has right child, then
// right child is nextRight of
// p and we also need to set
// nextRight of right child
if (q->right)
q->left->nextRight = q->right;
else
q->left->nextRight = getNextRight(q);
}
if (q->right)
q->right->nextRight = getNextRight(q);
// Set nextRight for other
// nodes in pre order fashion
q = q->nextRight;
}
// start from the first
// node of next level
if (p->left)
p = p->left;
else if (p->right)
p = p->right;
else
p = getNextRight(p);
}
}
/* Driver code*/
int main()
{
/* Constructed binary tree is
10
/ \
8 2
/ \
3 90
*/
node *root = new node(10);
root->left = new node(8);
root->right = new node(2);
root->left->left = new node(3);
root->right->right = new node(90);
// Populates nextRight pointer in all nodes
connectRecur(root);
// Let us check the values of nextRight pointers
cout << "Following are populated nextRight pointers in the tree"
" (-1 is printed if there is no nextRight) \n";
cout << "nextRight of " << root->data << " is "
<< (root->nextRight? root->nextRight->data: -1) <<endl;
cout << "nextRight of " << root->left->data << " is "
<< (root->left->nextRight? root->left->nextRight->data: -1) << endl;
cout << "nextRight of " << root->right->data << " is "
<< (root->right->nextRight? root->right->nextRight->data: -1) << endl;
cout << "nextRight of " << root->left->left->data<< " is "
<< (root->left->left->nextRight? root->left->left->nextRight->data: -1) << endl;
cout << "nextRight of " << root->right->right->data << " is "
<< (root->right->right->nextRight? root->right->right->nextRight->data: -1) << endl;
return 0;
}
// This code is contributed by rathbhupendra | constant | linear |
/* Iterative program to connect all the adjacent nodes at
* the same level in a binary tree*/
#include <iostream>
#include <queue>
using namespace std;
// A Binary Tree Node
class node {
public:
int data;
node* left;
node* right;
node* nextRight;
/* Constructor that allocates a new node with the
given data and NULL left and right pointers. */
node(int data)
{
this->data = data;
this->left = NULL;
this->right = NULL;
this->nextRight = NULL;
}
};
// setting right pointer to next right node
/*
10 ----------> NULL
/ \
8 --->2 --------> NULL
/
3 ----------------> NULL
*/
void connect(node* root)
{
// Base condition
if (root == NULL)
return;
// Create an empty queue like level order traversal
queue<node*> q;
q.push(root);
while (!q.empty()) {
// size indicates no. of nodes at current level
int size = q.size();
// for keeping track of previous node
node* prev = NULL;
while (size--) {
node* temp = q.front();
q.pop();
if (temp->left)
q.push(temp->left);
if (temp->right)
q.push(temp->right);
if (prev != NULL)
prev->nextRight = temp;
prev = temp;
}
prev->nextRight = NULL;
}
}
int main()
{
/* Constructed binary tree is
10
/ \
8 2
/
3
*/
// Let us create binary tree shown above
node* root = new node(10);
root->left = new node(8);
root->right = new node(2);
root->left->left = new node(3);
connect(root);
// Let us check the values
// of nextRight pointers
cout << "Following are populated nextRight pointers in "
"the tree"
" (-1 is printed if there is no nextRight)\n";
cout << "nextRight of " << root->data << " is "
<< (root->nextRight ? root->nextRight->data : -1)
<< endl;
cout << "nextRight of " << root->left->data << " is "
<< (root->left->nextRight
? root->left->nextRight->data
: -1)
<< endl;
cout << "nextRight of " << root->right->data << " is "
<< (root->right->nextRight
? root->right->nextRight->data
: -1)
<< endl;
cout << "nextRight of " << root->left->left->data
<< " is "
<< (root->left->left->nextRight
? root->left->left->nextRight->data
: -1)
<< endl;
return 0;
}
// this code is contributed by Kapil Poonia | linear | linear |
// C++ implementation to find the level
// having maximum number of Nodes
#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;
struct Node* right;
};
/* 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 = new Node;
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
// function to find the level
// having maximum number of Nodes
int maxNodeLevel(Node *root)
{
if (root == NULL)
return -1;
queue<Node *> q;
q.push(root);
// Current level
int level = 0;
// Maximum Nodes at same level
int max = INT_MIN;
// Level having maximum Nodes
int level_no = 0;
while (1)
{
// Count Nodes in a level
int NodeCount = q.size();
if (NodeCount == 0)
break;
// If it is maximum till now
// Update level_no to current level
if (NodeCount > max)
{
max = NodeCount;
level_no = level;
}
// Pop complete current level
while (NodeCount > 0)
{
Node *Node = q.front();
q.pop();
if (Node->left != NULL)
q.push(Node->left);
if (Node->right != NULL)
q.push(Node->right);
NodeCount--;
}
// Increment for next level
level++;
}
return level_no;
}
// Driver program to test above
int main()
{
// binary tree formation
struct Node *root = newNode(2); /* 2 */
root->left = newNode(1); /* / \ */
root->right = newNode(3); /* 1 3 */
root->left->left = newNode(4); /* / \ \ */
root->left->right = newNode(6); /* 4 6 8 */
root->right->right = newNode(8); /* / */
root->left->right->left = newNode(5);/* 5 */
printf("Level having maximum number of Nodes : %d",
maxNodeLevel(root));
return 0;
} | linear | linear |
// C++ code for the above approach
#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 val;
struct Node *left, *right;
};
// Initialising a map with key as levels of the tree
map<int, pair<double, double> > mp;
void avg(Node* r, int l)
{
// If the node is NULL
if (r == NULL)
return;
// Add the current value to the sum of this level
mp[l].first += r->val;
// Increase the number of elements in the current level
mp[l].second++;
// Traverse left
avg(r->left, l + 1);
// Traverse right
avg(r->right, l + 1);
}
void averageOfLevels(Node* root)
{
avg(root, 0);
// Travaersing for levels in map
for (auto i : mp) {
// Printing average of all levels
cout << (i.second.first / i.second.second) << ' ';
}
}
// Function to create a new node
Node* newNode(int data)
{
Node* temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
int main()
{
/* Let us construct a Binary Tree
4
/ \
2 9
/ \ \
3 5 7 */
Node* root = NULL;
root = newNode(4);
root->left = newNode(2);
root->right = newNode(9);
root->left->left = newNode(3);
root->left->right = newNode(8);
root->right->right = newNode(7);
// Function Call
averageOfLevels(root);
}
// This Code has been contributed by Alok Khansali | logn | nlogn |
// C++ implementation to print largest
// value in each level of Binary Tree
#include <bits/stdc++.h>
using namespace std;
// structure of a node of binary tree
struct Node {
int data;
Node *left, *right;
};
// function to get a new node
Node* newNode(int data)
{
// allocate space
Node* temp = new Node;
// put in the data
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// function to print largest value
// in each level of Binary Tree
void largestValueInEachLevel(Node* root)
{
// if tree is empty
if (!root)
return;
queue<Node*> q;
int nc, max;
// push root to the queue 'q'
q.push(root);
while (1) {
// node count for the current level
nc = q.size();
// if true then all the nodes of
// the tree have been traversed
if (nc == 0)
break;
// maximum element for the current
// level
max = INT_MIN;
while (nc--) {
// get the front element from 'q'
Node* front = q.front();
// remove front element from 'q'
q.pop();
// if true, then update 'max'
if (max < front->data)
max = front->data;
// if left child exists
if (front->left)
q.push(front->left);
// if right child exists
if (front->right)
q.push(front->right);
}
// print maximum element of
// current level
cout << max << " ";
}
}
// Driver code
int main()
{
/* Construct a Binary Tree
4
/ \
9 2
/ \ \
3 5 7 */
Node* root = NULL;
root = newNode(4);
root->left = newNode(9);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->right = newNode(7);
// Function call
largestValueInEachLevel(root);
return 0;
} | constant | linear |
// C++ program to Get Level of a node in a Binary Tree
#include <bits/stdc++.h>
using namespace std;
/* A tree node structure */
struct node {
int data;
struct node* left;
struct node* right;
};
// Helper function for getLevel(). It returns level of the
// data if data is present in tree, otherwise returns 0.
int getLevelUtil(struct node* node, int data, int level)
{
if (node == NULL)
return 0;
if (node->data == data)
return level;
int downlevel
= getLevelUtil(node->left, data, level + 1);
if (downlevel != 0)
return downlevel;
downlevel = getLevelUtil(node->right, data, level + 1);
return downlevel;
}
/* Returns level of given data value */
int getLevel(struct node* node, int data)
{
return getLevelUtil(node, data, 1);
}
// Utility function to create a new Binary Tree node
struct node* newNode(int data)
{
struct node* temp = new struct node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// Driver Code
int main()
{
struct node* root = new struct node;
int x;
// Constructing tree given in the above figure
root = newNode(3);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(1);
root->left->right = newNode(4);
for (x = 1; x <= 5; x++) {
int level = getLevel(root, x);
if (level)
cout << "Level of " << x << " is " << level
<< endl;
else
cout << x << "is not present in tree" << endl;
}
getchar();
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129) | linear | linear |
// C++ program to print level in which X is present in
// binary tree using STL
#include <bits/stdc++.h>
using namespace std;
// A Binary Tree Node
struct Node {
int data;
struct Node *left, *right;
};
int printLevel(Node* root, int X)
{
Node* node;
// Base Case
if (root == NULL)
return 0;
// Create an empty queue for level order traversal
queue<Node*> q;
// Create a var represent current level of tree
int currLevel = 1;
// Enqueue Root
q.push(root);
while (q.empty() == false) {
int size = q.size();
while (size--) {
node = q.front();
if (node->data == X)
return currLevel;
q.pop();
/* Enqueue left child */
if (node->left != NULL)
q.push(node->left);
/*Enqueue right child */
if (node->right != NULL)
q.push(node->right);
}
currLevel++;
}
return 0;
}
// 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;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in above diagram
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(7);
root->right->right = newNode(6);
cout << printLevel(root, 6);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129) | linear | linear |
// CPP program to print level of given node
// in binary tree iterative approach
/* Example binary tree
root is at level 1
20
/ \
10 30
/ \ / \
5 15 25 40
/
12 */
#include <bits/stdc++.h>
using namespace std;
// node of binary tree
struct node {
int data;
node* left;
node* right;
};
// utility function to create
// a new node
node* getnode(int data)
{
node* newnode = new node();
newnode->data = data;
newnode->left = NULL;
newnode->right = NULL;
}
// utility function to return level of given node
int getlevel(node* root, int data)
{
queue<node*> q;
int level = 1;
q.push(root);
// extra NULL is pushed to keep track
// of all the nodes to be pushed before
// level is incremented by 1
q.push(NULL);
while (!q.empty()) {
node* temp = q.front();
q.pop();
if (temp == NULL) {
if (q.front() != NULL) {
q.push(NULL);
}
level += 1;
} else {
if (temp->data == data) {
return level;
}
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
}
}
return 0;
}
int main()
{
// create a binary tree
node* root = getnode(20);
root->left = getnode(10);
root->right = getnode(30);
root->left->left = getnode(5);
root->left->right = getnode(15);
root->left->right->left = getnode(12);
root->right->left = getnode(25);
root->right->right = getnode(40);
// return level of node
int level = getlevel(root, 30);
(level != 0) ? (cout << "level of node 30 is " << level << endl) :
(cout << "node 30 not found" << endl);
level = getlevel(root, 12);
(level != 0) ? (cout << "level of node 12 is " << level << endl) :
(cout << "node 12 not found" << endl);
level = getlevel(root, 25);
(level != 0) ? (cout << "level of node 25 is " << level << endl) :
(cout << "node 25 not found" << endl);
level = getlevel(root, 27);
(level != 0) ? (cout << "level of node 27 is " << level << endl) :
(cout << "node 27 not found" << endl);
return 0;
} | linear | linear |
// C++ program to remove all half nodes
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node* left, *right;
};
struct node* newNode(int data)
{
node* nod = new node();
nod->data = data;
nod->left = nod->right = NULL;
return(nod);
}
void printInoder(struct node*root)
{
if (root != NULL)
{
printInoder(root->left);
cout<< root->data << " ";
printInoder(root->right);
}
}
// Removes all nodes with only one child and returns
// new root (note that root may change)
struct node* RemoveHalfNodes(struct node* root)
{
if (root==NULL)
return NULL;
root->left = RemoveHalfNodes(root->left);
root->right = RemoveHalfNodes(root->right);
if (root->left==NULL && root->right==NULL)
return root;
/* if current nodes is a half node with left
child NULL left, then it's right child is
returned and replaces it in the given tree */
if (root->left==NULL)
{
struct node *new_root = root->right;
free(root); // To avoid memory leak
return new_root;
}
/* if current nodes is a half node with right
child NULL right, then it's right child is
returned and replaces it in the given tree */
if (root->right==NULL)
{
struct node *new_root = root->left;
free(root); // To avoid memory leak
return new_root;
}
return root;
}
// Driver program
int main(void)
{
struct node*NewRoot=NULL;
struct node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left=newNode(1);
root->left->right->right=newNode(11);
root->right->right=newNode(9);
root->right->right->left=newNode(4);
cout<<"Inorder traversal of given tree \n";
printInoder(root);
NewRoot = RemoveHalfNodes(root);
cout<<"\nInorder traversal of the modified tree \n";
printInoder(NewRoot);
return 0;
} | constant | linear |
/* C++ program to pairwise swap
leaf nodes from left to right */
#include <bits/stdc++.h>
using namespace std;
// A Binary Tree Node
struct Node
{
int data;
struct Node *left, *right;
};
// function to swap two Node
void Swap(Node **a, Node **b)
{
Node * temp = *a;
*a = *b;
*b = temp;
}
// two pointers to keep track of
// first and second nodes in a pair
Node **firstPtr;
Node **secondPtr;
// function to pairwise swap leaf
// nodes from left to right
void pairwiseSwap(Node **root, int &count)
{
// if node is null, return
if (!(*root))
return;
// if node is leaf node, increment count
if(!(*root)->left&&!(*root)->right)
{
// initialize second pointer
// by current node
secondPtr = root;
// increment count
count++;
// if count is even, swap first
// and second pointers
if (count%2 == 0)
Swap(firstPtr, secondPtr);
else
// if count is odd, initialize
// first pointer by second pointer
firstPtr = secondPtr;
}
// if left child exists, check for leaf
// recursively
if ((*root)->left)
pairwiseSwap(&(*root)->left, count);
// if right child exists, check for leaf
// recursively
if ((*root)->right)
pairwiseSwap(&(*root)->right, count);
}
// 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 inorder traversal
// of binary tree
void printInorder(Node* node)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left);
/* then print the data of node */
printf("%d ", node->data);
/* now recur on right child */
printInorder(node->right);
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in
// above diagram
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(8);
root->right->left->left = newNode(6);
root->right->left->right = newNode(7);
root->right->right->left = newNode(9);
root->right->right->right = newNode(10);
// print inorder traversal before swapping
cout << "Inorder traversal before swap:\n";
printInorder(root);
cout << "\n";
// variable to keep track
// of leafs traversed
int c = 0;
// Pairwise swap of leaf nodes
pairwiseSwap(&root, c);
// print inorder traversal after swapping
cout << "Inorder traversal after swap:\n";
printInorder(root);
cout << "\n";
return 0;
} | linear | linear |
// C++ program to find the length of longest
// path with same values in 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 val;
struct Node *left, *right;
};
/* Function to print the longest path
of same values */
int length(Node *node, int *ans) {
if (!node)
return 0;
// Recursive calls to check for subtrees
int left = length(node->left, ans);
int right = length(node->right, ans);
// Variables to store maximum lengths in two directions
int Leftmax = 0, Rightmax = 0;
// If curr node and it's left child has same value
if (node->left && node->left->val == node->val)
Leftmax += left + 1;
// If curr node and it's right child has same value
if (node->right && node->right->val == node->val)
Rightmax += right + 1;
*ans = max(*ans, Leftmax + Rightmax);
return max(Leftmax, Rightmax);
}
/* Driver function to find length of
longest same value path*/
int longestSameValuePath(Node *root) {
int ans = 0;
length(root, &ans);
return ans;
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node *newNode(int data) {
Node *temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver code
int main() {
/* Let us construct a Binary Tree
4
/ \
4 4
/ \ \
4 9 5 */
Node *root = NULL;
root = newNode(4);
root->left = newNode(4);
root->right = newNode(4);
root->left->left = newNode(4);
root->left->right = newNode(9);
root->right->right = newNode(5);
cout << longestSameValuePath(root);
return 0;
} | logn | linear |
// C++ program to find distance of a given
// node from root.
#include <bits/stdc++.h>
using namespace std;
// A Binary Tree Node
struct Node
{
int data;
Node *left, *right;
};
// A utility function to create a new Binary
// Tree Node
Node *newNode(int item)
{
Node *temp = new Node;
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
// Returns -1 if x doesn't exist in tree. Else
// returns distance of x from root
int findDistance(Node *root, int x)
{
// Base case
if (root == NULL)
return -1;
// Initialize distance
int dist = -1;
// Check if x is present at root or in left
// subtree or right subtree.
if ((root->data == x) ||
(dist = findDistance(root->left, x)) >= 0 ||
(dist = findDistance(root->right, x)) >= 0)
return dist + 1;
return dist;
}
// Driver Program to test above functions
int main()
{
Node *root = newNode(5);
root->left = newNode(10);
root->right = newNode(15);
root->left->left = newNode(20);
root->left->right = newNode(25);
root->left->right->right = newNode(45);
root->right->left = newNode(30);
root->right->right = newNode(35);
cout << findDistance(root, 45);
return 0;
} | constant | linear |
// C program to print right sibling of a node
#include <bits/stdc++.h>
// A Binary Tree Node
struct Node {
int data;
Node *left, *right, *parent;
};
// A utility function to create a new Binary
// Tree Node
Node* newNode(int item, Node* parent)
{
Node* temp = new Node;
temp->data = item;
temp->left = temp->right = NULL;
temp->parent = parent;
return temp;
}
// Method to find right sibling
Node* findRightSibling(Node* node, int level)
{
if (node == NULL || node->parent == NULL)
return NULL;
// GET Parent pointer whose right child is not
// a parent or itself of this node. There might
// be case when parent has no right child, but,
// current node is left child of the parent
// (second condition is for that).
while (node->parent->right == node
|| (node->parent->right == NULL
&& node->parent->left == node)) {
if (node->parent == NULL
|| node->parent->parent == NULL)
return NULL;
node = node->parent;
level--;
}
// Move to the required child, where right sibling
// can be present
node = node->parent->right;
if (node == NULL)
return NULL;
// find right sibling in the given subtree(from current
// node), when level will be 0
while (level < 0) {
// Iterate through subtree
if (node->left != NULL)
node = node->left;
else if (node->right != NULL)
node = node->right;
else
// if no child are there, we cannot have right
// sibling in this path
break;
level++;
}
if (level == 0)
return node;
// This is the case when we reach 9 node in the tree,
// where we need to again recursively find the right
// sibling
return findRightSibling(node, level);
}
// Driver Program to test above functions
int main()
{
Node* root = newNode(1, NULL);
root->left = newNode(2, root);
root->right = newNode(3, root);
root->left->left = newNode(4, root->left);
root->left->right = newNode(6, root->left);
root->left->left->left = newNode(7, root->left->left);
root->left->left->left->left = newNode(10, root->left->left->left);
root->left->right->right = newNode(9, root->left->right);
root->right->right = newNode(5, root->right);
root->right->right->right = newNode(8, root->right->right);
root->right->right->right->right = newNode(12, root->right->right->right);
// passing 10
Node* res = findRightSibling(root->left->left->left->left, 0);
if (res == NULL)
printf("No right sibling");
else
printf("%d", res->data);
return 0;
} | constant | linear |
/* C++ program to find next right of a given key
using preorder traversal */
#include <bits/stdc++.h>
using namespace std;
// A Binary Tree Node
struct Node {
struct Node *left, *right;
int key;
};
// Utility function to create a new tree node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
// Function to find next node for given node
// in same level in a binary tree by using
// pre-order traversal
Node* nextRightNode(Node* root, int k, int level,
int& value_level)
{
// return null if tree is empty
if (root == NULL)
return NULL;
// if desired node is found, set value_level
// to current level
if (root->key == k) {
value_level = level;
return NULL;
}
// if value_level is already set, then current
// node is the next right node
else if (value_level) {
if (level == value_level)
return root;
}
// recurse for left subtree by increasing level by 1
Node* leftNode = nextRightNode(root->left, k,
level + 1, value_level);
// if node is found in left subtree, return it
if (leftNode)
return leftNode;
// recurse for right subtree by increasing level by 1
return nextRightNode(root->right, k, level + 1,
value_level);
}
// Function to find next node of given node in the
// same level in given binary tree
Node* nextRightNodeUtil(Node* root, int k)
{
int value_level = 0;
return nextRightNode(root, k, 1, value_level);
}
// A utility function to test above functions
void test(Node* root, int k)
{
Node* nr = nextRightNodeUtil(root, k);
if (nr != NULL)
cout << "Next Right of " << k << " is "
<< nr->key << endl;
else
cout << "No next right node found for "
<< k << endl;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree given in the
// above example
Node* root = newNode(10);
root->left = newNode(2);
root->right = newNode(6);
root->right->right = newNode(5);
root->left->left = newNode(8);
root->left->right = newNode(4);
test(root, 10);
test(root, 2);
test(root, 6);
test(root, 5);
test(root, 8);
test(root, 4);
return 0;
} | constant | linear |
// CPP Program to find Tilt of 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 val;
struct Node *left, *right;
};
/* Recursive function to calculate Tilt of
whole tree */
int traverse(Node* root, int* tilt)
{
if (!root)
return 0;
// Compute tilts of left and right subtrees
// and find sums of left and right subtrees
int left = traverse(root->left, tilt);
int right = traverse(root->right, tilt);
// Add current tilt to overall
*tilt += abs(left - right);
// Returns sum of nodes under current tree
return left + right + root->val;
}
/* Driver function to print Tilt of whole tree */
int Tilt(Node* root)
{
int tilt = 0;
traverse(root, &tilt);
return tilt;
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node* newNode(int data)
{
Node* temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver code
int main()
{
/* Let us construct a Binary Tree
4
/ \
2 9
/ \ \
3 5 7 */
Node* root = NULL;
root = newNode(4);
root->left = newNode(2);
root->right = newNode(9);
root->left->left = newNode(3);
root->left->right = newNode(8);
root->right->right = newNode(7);
cout << "The Tilt of whole tree is " << Tilt(root);
return 0;
} | linear | linear |
// C++ program to find averages of all levels
// in 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;
};
string inorder(Node* node, unordered_map<string, int>& m)
{
if (!node)
return "";
string str = "(";
str += inorder(node->left, m);
str += to_string(node->data);
str += inorder(node->right, m);
str += ")";
// Subtree already present (Note that we use
// unordered_map instead of unordered_set
// because we want to print multiple duplicates
// only once, consider example of 4 in above
// subtree, it should be printed only once.
if (m[str] == 1)
cout << node->data << " ";
m[str]++;
return str;
}
// Wrapper over inorder()
void printAllDups(Node* root)
{
unordered_map<string, int> m;
inorder(root, m);
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver code
int main()
{
Node* root = NULL;
root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(2);
root->right->left->left = newNode(4);
root->right->right = newNode(4);
printAllDups(root);
return 0;
} | quadratic | quadratic |
// CPP program to find largest three elements in
// a binary tree.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left;
struct Node *right;
};
/* 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 = new Node;
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
// function to find three largest element
void threelargest(Node *root, int &first, int &second,
int &third) {
if (root == NULL)
return;
// if data is greater than first large number
// update the top three list
if (root->data > first) {
third = second;
second = first;
first = root->data;
}
// if data is greater than second large number
// and not equal to first update the bottom
// two list
else if (root->data > second && root->data != first) {
third = second;
second = root->data;
}
// if data is greater than third large number
// and not equal to first & second update the
// third highest list
else if (root->data > third &&
root->data != first &&
root->data != second)
third = root->data;
threelargest(root->left, first, second, third);
threelargest(root->right, first, second, third);
}
// driver function
int main() {
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(4);
root->right->right = newNode(5);
int first = 0, second = 0, third = 0;
threelargest(root, first, second, third);
cout << "three largest elements are "
<< first << " " << second << " "
<< third;
return 0;
} | constant | linear |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.