Tree
Tree
Suppose we want
to show the employees and their positions in the hierarchical form then it can be represented
as shown below:
The above tree shows the organization hierarchy of some company. In the above structure,
john is the CEO of the company, and John has two direct reports named as Steve and Rohan.
Steve has three direct reports named Lee, Bob, Ella where Steve is a manager. Bob has two
direct reports named Sal and Emma. Emma has two direct reports named Tom and Raj.
Tom has one direct report named Bill. This particular logical structure is known as a Tree.
Its structure is similar to the real tree, so it is named a Tree. In this structure, the root is at
the top, and its branches are moving in a downward direction. Therefore, we can say that the
Tree data structure is an efficient way of storing the data in a hierarchical way.
• Root: The root node is the topmost node in the tree hierarchy. In other words, the
root node is the one that doesn't have any parent. In the above structure, node
numbered 1 is the root node of the tree. If a node is directly linked to some other
node, it would be called a parent-child relationship.
• Child node: If the node is a descendant of any node, then the node is known as a child
node.
• Parent: If the node contains any sub-node, then that node is said to be the parent of
that sub-node.
• Sibling: The nodes that have the same parent are known as siblings.
• Leaf Node:- The node of the tree, which doesn't have any child node, is called a leaf
node. A leaf node is the bottom-most node of the tree. There can be any number of
leaf nodes present in a general tree. Leaf nodes can also be called external nodes.
• Internal nodes: A node has atleast one child node known as an internal
• Ancestor node:- An ancestor of a node is any predecessor node on a path from the
root to that node. The root node doesn't have any ancestors. In the tree shown in the
above image, nodes 1, 2, and 5 are the ancestors of node 10.
• Descendant: The immediate successor of the given node is known as a descendant of
a node. In the above figure, 10 is the descendant of node 5.
Recursive data structure: The tree is also known as a recursive data structure. A tree
can be defined as recursively because the distinguished node in a tree data structure is
known as a root node. The root node of the tree contains a link to all the roots of its
subtrees. The left subtree is shown in the yellow color in the below figure, and the right
subtree is shown in the red color. The left subtree can be further split into subtrees shown
in three different colors. Recursion means reducing something in a self-similar manner. So,
this recursive property of the tree data structure is implemented in various applications.
• Number of edges: If there are n nodes, then there would n-1 edges. Each arrow in
the structure represents the link or path. Each node, except the root node, will have
at least one incoming link known as an edge. There would be one link for the parent-
child relationship.
• Depth of node x: The depth of node x can be defined as the length of the path from
the root to the node x. One edge contributes one-unit length in the path. So, the depth
of node x can also be defined as the number of edges between the root node and the
node x. The root node has 0 depth.
• Height of node x: The height of node x can be defined as the longest path from the
node x to the leaf node.
General tree: The general tree is one of the types of tree data structure. In the general tree,
a node can have either 0 or maximum n number of nodes. There is no restriction imposed
on the degree of the node (the number of nodes that a node can contain).
There can be n number of subtrees in a general tree. In the general tree, the subtrees are
unordered as the nodes in the subtree cannot be ordered.
Binary tree: Here, binary name itself suggests two numbers, i.e., 0 and 1. In a binary tree,
each node in a tree can have utmost two child nodes. Here, utmost means whether the node
has 0 nodes, 1 node or 2 nodes.
AVL tree
It is one of the types of the binary tree, or we can say that it is a variant of the binary search
tree. AVL tree satisfies the property of the binary tree as well as of the binary search tree.
It is a self-balancing binary search tree that was invented by Adelson Velsky Lindas. Here,
self-balancing means that balancing the heights of left subtree and right subtree. This
balancing is measured in terms of the balancing factor.
We can consider a tree as an AVL tree if the tree obeys the binary search tree as well as a
balancing factor. The balancing factor can be defined as the difference between the height
of the left subtree and the height of the right subtree. The balancing factor's value must be
either 0, -1, or 1; therefore, each node in the AVL tree should have the value of the balancing
factor either as 0, -1, or 1.
Red-Black Tree
The red-Black tree is the binary search tree. The prerequisite of the Red-Black tree is that
we should know about the binary search tree. In a binary search tree, the value of the left-
subtree should be less than the value of that node, and the value of the right-subtree should
be greater than the value of that node. As we know that the time complexity of binary search
in the average case is log2n, the best case is O(1), and the worst case is O(n).
When any operation is performed on the tree, we want our tree to be balanced so that all the
operations like searching, insertion, deletion, etc., take less time, and all these operations will
have the time complexity of log2n.
The red-black tree is a self-balancing binary search tree. AVL tree is also a height balancing
binary search tree then why do we require a Red-Black tree. In the AVL tree, we do not
know how many rotations would be required to balance the tree, but in the Red-black tree,
a maximum of 2 rotations are required to balance the tree. It contains one extra bit that
represents either the red or black color of a node to ensure the balancing of the tree.
Splay tree
The splay tree data structure is also binary search tree in which recently accessed element
is placed at the root position of tree by performing some rotation operations. Here, splaying
means the recently accessed node. It is a self-balancing binary search tree having no explicit
balance condition like AVL tree.
It might be a possibility that height of the splay tree is not balanced, i.e., height of both left
and right subtrees may differ, but the operations in splay tree takes order of logN time where
n is the number of nodes.
Splay tree is a balanced tree but it cannot be considered as a height balanced tree because
after each operation, rotation is performed which leads to a balanced tree.
Treap
Treap data structure came from the Tree and Heap data structure. So, it comprises the
properties of both Tree and Heap data structures. In Binary search tree, each node on the left
subtree must be equal or less than the value of the root node and each node on the right
subtree must be equal or greater than the value of the root node. In heap data structure, both
right and left subtrees contain larger keys than the root; therefore, we can say that the root
node contains the lowest value.
In treap data structure, each node has both key and priority where key is derived from the
Binary search tree and priority is derived from the heap data structure.
The Treap data structure follows two properties which are given below:
• Right child of a node>=current node and left child of a node <=current node (binary
tree)
• Children of any subtree must be greater than the node (heap)
B-tree
B-tree is a balanced m-way tree where m defines the order of the tree. Till now, we read that
the node contains only one key but b-tree can have more than one key, and more than 2
children. It always maintains the sorted data. In binary tree, it is possible that leaf nodes can
be at different levels, but in b-tree, all the leaf nodes must be at the same level.
The root node must contain minimum 1 key and all other nodes must contain atleast ceiling
of m/2 minus 1 keys.
Implementation of Tree
The tree data structure can be created by creating the nodes dynamically with the help of the
pointers. The tree in the memory can be represented as shown below:
In programming, the structure of a node can be defined as:
struct node
{
int data;
struct node *left;
struct node *right;
}
Inorder Traversal
Inorder traversal visits the node in the order: Left -> Root -> Right
return inorder;
}
Preorder Traversal
Preorder traversal visits the node in the order: Root -> Left -> Right
} }}
return ans; }
Postorder Traversal
}
Level Order Traversal
Level Order Traversal visits all nodes present in the same level completely before visiting the
next level.
Level Order Traversal - Naukri Code 360 Binary Tree Level Order Traversal - LeetCode
} if(temp->right != NULL){
if(temp -> right != NULL){ q.push(temp->right);
q.push(temp-> right); }
} }
ans.push_back(level);
} }
Questions
110. Balanced Binary Tree (the idea is to use any traversal along with height function)
543. Diameter of Binary Tree(the idea is to use any traversal and calculate lh + rh for each
node by using height function)
Har node pe do options hain ya to wo answer bane ya sahi path batade. Agar answer banna
hai to leftsum ko jodo , right sum lo aur root ki value ko aur kyunki aisi bht si node hain to
sabka maximum lelo like this maxi = max(maxi , root->val + leftsum + rightsum);
Aur agar answer nhin banna hai to return kardo root ki value plus max of left sum , right sum
(just use level order with an index that track end of each level and use if(ind %2 == 0) then
reverse the level then push)
inorder(root->left, boundaries);
if(root->left == nullptr && root->right==nullptr){
boundaries.push_back(root->data);
}
inorder(root -> right , boundaries);
}
vector<int> tempo;
temp = root->right;
while(temp != nullptr){
if(!(temp -> left == nullptr && temp -> right == nullptr))
tempo.push_back(temp -> data);
if(temp->right != nullptr) temp = temp -> right;
else temp = temp -> left;
}
reverse(tempo.begin(), tempo.end());
for(int i=0; i<tempo.size(); i++){
boundaries.push_back(tempo[i]);
}
Its more like a data structure question which involve multiset , queue , map;, the idea is
simple use level order traversal and keep putting element in their desired position.
use concept of vertical line and store in a map if a line is visited , if it is visited then don’t pick
element from that line and use map also not unordered_map because we need element of
farthest line first that is we need element in line wise like , first we need element from line -
3 then -2 , -1 , 0 , 1, 2) so on , so map stores in sorted order that’s why use map.
We can do this by level order traversal as well as with reverse pre order traversal Level order
traversal is not recommended due to its space complexity. The idea is to pick only one
element from each level. So ham ek data structure bana lenge aur har level pe ek baar hi
insert ho iske liye if(level == res.size()) res.push_back( root -> val); ye condition lagayenge.
Jab same level pe left ki taraf se aayega to data structure me kai elements honge aur ye
condition match nhin hogi , isliye enter nhin hoga naya element.
When moving left in one sub tree , move right in another subtree to compare the values.
if (hasPath(root->left, arr, x) ||
hasPath(root->right, arr, x))
return true;
arr.pop_back();
return false;
}
Har node ya to null return kar rahi hai ya agar no mil jata hai to wo number return kar rahi hai.
Lca(4,7) →
6 node donon taraf se null return kar rahi hai, 7 node 7 return kar rahi hai kyunki lca(4,7)
nikalna hai. 5 node men ek taraf null hai ek taraf 7 , to 5 node bhi 7 return karegi.
(ismen har node ko index dete hain if parent index is i then left child 2*i + 1 and right 2*i + 2)
but ye karne se bht badi values aati hain isliye har level pe ek fixed value minus kar dete hain
taki phir values range men aayen.
int widthOfBinaryTree(TreeNode* root) {
if(!root) return 0;
int width = 1;
queue<pair<TreeNode*,int>> q;
q.push({root,0});
while(!q.empty()){
q.pop();
if(node -> left != nullptr) q.push({node -> left , 2LL * index + 1});
if(node -> right != nullptr) q.push({node -> right , 2LL * index + 2});
return width;
}
Check for Children Sum Property in a Binary Tree
Output: [7,4,1]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values
7, 4, and 1.
Sol:
}
}
vector<int> ans;
while (!q.empty()) {
ans.push_back(q.front()->val);
q.pop();
}
return ans;
}
}
return d-1;
}
string s = "";
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode * temp = q.front();
q.pop();
if(temp == nullptr) s.append("#,");
else s.append(to_string(temp->val) + ',');
if(temp != nullptr) {
q.push(temp -> left);
q.push(temp -> right);
}
}
cout << s ;
return s;
}
getline(s,str,',');
if(str == "#"){
node -> left = nullptr;
}
else{
TreeNode * leftnode = new TreeNode(stoi(str));
node ->left = leftnode;
q.push(leftnode);
}
getline(s,str,',');
if(str == "#"){
node -> right = nullptr;
}
else{
TreeNode* rightnode = new TreeNode(stoi(str));
node -> right = rightnode;
q.push(rightnode);
}
}
return root;
}
https://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion-and-without-
stack/
Int solve(Node* root , int & res this variable should be passed by address and it will store
the answer to all dp on tree problem)
{ If(root == nullptr) {
Base Return 0
Condition }