SlideShare a Scribd company logo
1 of 15
1 http://coursehunt.net/
Data Structures​.
1: A Tree Is Typically Traversed In Two Ways​:
A)​ ​Breadth First Traversal​:- This traversal visits nodes by levels from top to bottom and
from left to right.
B) Depth-First Traversal:
There are three different types of depth-first traversals:
PreOrder traversal​ - visit the parent first and then left and right children.
InOrder traversal​ - visit the left child, then the parent and the right child.
PostOrder traversal​ - visit left child, then the right child and then the parent.
Breadth-First Traversal:
This traversal visits nodes by levels from top to bottom and from left to right.
PreOrder - 8, 5, 9, 7, 1, 12, 2, 4, 11, 3
InOrder - 9, 5, 1, 7, 2, 12, 8, 4, 3, 11
PostOrder - 9, 1, 2, 12, 7, 5, 3, 11, 4, 8
LevelOrder - 8, 5, 4, 9, 7, 11, 1, 12, 3, 2
In Below picture, we demonstrate the order of node visitation. Number 1 denotes
the first node in a particular traversal and 7 denote the last node.
2 http://coursehunt.net/
Depth-First Traversal:
There are three different types of depth-first traversals, :
● PreOrder traversal - visit the parent first and then left and right children;
● InOrder traversal - visit the left child, then the parent and the right child;
● PostOrder traversal - visit left child, then the right child and then the parent;
2: Searching Into a Binary Tree:
If we want to search for a node whose key is K, start searching from the root of the binary
search tree.
If the root is NULL, the search contains no nodes and the search is unsuccessful. Otherwise,
compare k with the key in root.
If k equals the root's key, then search is successful. If k is less than root's key, then no
element in the right sub tree can have a key value equal to k, therefore we search the left sub
tree of a root.
If k is larger than root's key value, search the right subtree of the root.
Pseudocode for recursive search of a binary search​ ​tree​:
element *search(treePointer root, int key) {
if(!root) return NULL;
if(k==root->data.key) return &(root->data);
if(k<root->data.key)
return search(root->leftchild, k);
return search(root->rightchild, k);
}
3 http://coursehunt.net/
3: ​Inserting into a binary search tree:
● Check whether root node is present or not(tree available or not). If root is NULL,
create root node.
● If the element to be inserted is less than the element present in the root node, traverse
the left sub-tree recursively until we reach T->left/T->right is NULL and place the new node
at T->left(key in new node < key in T)/T->right (key in new node > key in T).
● If the element to be inserted is greater than the element present in root node, traverse
the right sub-tree recursively until we reach T->left/T->right is NULL and place the new
node at T->left/T->right.
Pseudocode:
TreeNode insert(int data, TreeNode T) {
if T is NULL {
T = (TreeNode *)malloc(sizeof (Struct TreeNode));
(Allocate Memory of new node and load the data into it)
T->data = data;
T->left = NULL;
T->right = NULL;
} else if T is less than T->left {
T->left = insert(data, T->left);
(Then node needs to be inserted in left sub-tree.So,
recursively traverse left sub-tree to find the place
where the new node needs to be inserted)
} else if T is greater than T->right {
T->right = insert(data, T->right);
(Then node needs to be inserted in right sub-tree
So, recursively traverse right sub-tree to find the
place where the new node needs to be inserted.)
}
return T;
}
4 http://coursehunt.net/
4: Checking if two binary trees are same:
● Two trees are identical when they have same data and arrangement of data is also same.
Pseudocode:
sameTree(tree1, tree2)
1. If both trees are empty then return 1.
2. Else If both trees are non -empty
(a) Check data of the root nodes (tree1->data == tree2->data)
(b) Check left subtrees recursively i.e., call sameTree(
tree1->left_subtree, tree2->left_subtree)
(c) Check right subtrees recursively i.e., call sameTree(
tree1->right_subtree, tree2->right_subtree)
(d) If a,b and c are true then return 1.
3 Else return 0 (one is empty and other is not)
Time Complexity:
Complexity of the identicalTree() will be according to the tree with lesser number of
nodes. Let number of nodes in two trees be m and n then complexity of sameTree() is O(m)
where m < n
5: Find size of binary tree:
● Start from the root.
● Size = 1 (for the root) + Size Of left Sub-Tree + Size Of right Sub-Tree
● solve the left sub-tree and right sub-tree recursively​.
● Size of a tree = Size of left subtree + 1 + Size of right subtree
5 http://coursehunt.net/
6: Find height of binary tree:
● Get the height of left sub tree, say leftHeight
● Get the height of right sub tree, say rightHeight
● Take the Max(leftHeight, rightHeight) and add 1 for the root and return
● Call recursively.
6 http://coursehunt.net/
7: Root to leaf sum of Binary tree:
7 http://coursehunt.net/
● Given a binary tree and a number, return true if the tree has a root-to-leaf path such that
adding up all the values along the path equals the given number. Return false if no such path
can be found.
Ex:
in the above tree root to leaf paths exist with following sums.
21 –> 10 – 8 – 3
23 –> 10 – 8 – 5
14 –> 10 – 2 – 2
So the returned value should be true only for numbers 21, 23 and 14. For any other number,
returned value should be false.
Algorithm:
Recursively check if left or right child has path sum equal to ( number – value at current
node)
8: Check if binary tree is a binary search tree:
A binary search tree (BST) is a node based binary tree data structure which has the following
properties.
• The left subtree of a node contains only nodes with keys less than the node’s key.
• The right subtree of a node contains only nodes with keys greater than the node’s key.
• Both the left and right subtrees must also be binary search trees.
From the above properties it naturally follows that:
• Each node (item in the tree) has a distinct key​.
Pseudocode:
8 http://coursehunt.net/
/* Returns true if the given tree is a binary search tree
(efficient version). */
int isBST(struct node* node)
{
return(isBSTUtil(node, INT_MIN, INT_MAX));
}
/* Returns true if the given tree is a BST and its
values are >= min and <= max. */
int isBSTUtil(struct node* node, int min, int max)
9: Level order traversal of binary tree:
Level order traversal of the above tree is 1 2 3 4 5
Algorithm:
/*Function to print level order traversal of tree*/
printLevelorder(tree)
for d = 1 to height(tree)
printGivenLevel(tree, d);
/*Function to print all nodes at a given level*/
printGivenLevel(tree, level)
if tree is NULL then return;
if level is 1, then
print(tree->data);
else if level greater than 1, then
printGivenLevel(tree->left, level-1);
printGivenLevel(tree->right, level-1);
METHOD 2 (Use Queue):
For each node, first the node is visited and then it’s child nodes are put in a FIFO queue.
printLevelorder(tree)
1) Create an empty queue q
2) temp_node = root /*start from root*/
3) Loop while temp_node is not NULL
a) print temp_node->data.
b) Enqueue temp_node’s children (first left then right children) to q
c) Dequeue a node from q and assign it’s value to temp_node
9 http://coursehunt.net/
10: Iterative PostOrder traversal of binary tree:
The key to to iterative postorder traversal is the following:
1. The order of "Postorder" is: left child -> right child -> parent node.
2. Find the relation between the previously visited node and the current node
3. Use a stack to track nodes
As we go down the tree to the left, check the previously visited node. If the current node is
the left or right child of the previous node, then keep going down the tree, and add left/right
node to stack when applicable. When there are no children for current node, i.e., the current
node is a leaf, pop it from the stack. Then the previous node become to be under the current
node for next loop
Ex:
1. Push 1 to first stack.
First stack: 1
Second stack: Empty
2. Pop 1 from first stack and push it to second stack.
Push left and right children of 1 to first stack
First stack: 2, 3
Second stack: 1
3. Pop 3 from first stack and push it to second stack.
Push left and right children of 3 to first stack
First stack: 2, 6, 7
Second stack:1, 3
4. Pop 7 from first stack and push it to second stack.
First stack: 2, 6
Second stack:1, 3, 7
5. Pop 6 from first stack and push it to second stack.
First stack: 2
Second stack:1, 3, 7, 6
6. Pop 2 from first stack and push it to second stack.
10 http://coursehunt.net/
Push left and right children of 2 to first stack
First stack: 4, 5
Second stack:1, 3, 7, 6, 2
7. Pop 5 from first stack and push it to second stack.
First stack: 4
Second stack: 1, 3, 7, 6, 2, 5
8. Pop 4 from first stack and push it to second stack.
First stack: Empty
Second stack: 1, 3, 7, 6, 2, 5, 4
The algorithm stops since there is no more item in first stack.
Observe that content of second stack is in postorder fashion. Print them.
11: Iterative Preorder traversal of binary tree:
1. Create a Stack.
2. Print the root and push it to Stack and go left i.e root=root.left and till it hits the NULL.
3. If root is null and Stack is empty Then
1. return, we are done.
4. Else
1. Pop the top Node from the Stack and set it as, root = popped_Node.
2. Go right, root = root.right.
3. Go to step 2.
5. End If
Code:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
11 http://coursehunt.net/
}
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> returnList = new ArrayList<Integer>();
if(root == null)
return returnList;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.empty()){
TreeNode n = stack.pop();
returnList.add(n.val);
if(n.right != null){
stack.push(n.right);
}
if(n.left != null){
stack.push(n.left);
}
}
return returnList;
}
}
12: Iterative Inorder traversal of binary tree:
Create an empty stack S.
2) Initialize current node as root
3) Push the current node to S and set current = current->left until current is NULL
4) If current is NULL and stack is not empty then
a) Pop the top item from stack.
b) Print the popped item, set current = popped_item->right
c) Go to step 3.
5) If current is NULL and stack is empty then we are done.
Ex:
1
/ 
2 3
/ 
4 5
Step 1 Creates an empty stack: S = NULL
Step 2 sets current as address of root: current -> 1
12 http://coursehunt.net/
Step 3 Pushes the current node and set current = current->left until current is NULL
current -> 1
push 1: Stack S -> 1
current -> 2
push 2: Stack S -> 2, 1
current -> 4
push 4: Stack S -> 4, 2, 1
current = NULL
Step 4 pops from S
a) Pop 4: Stack S -> 2, 1
b) print "4"
c) current = NULL /*right of 4 */ and go to step 3
Since current is NULL step 3 doesn't do anything.
Step 4 pops again.
a) Pop 2: Stack S -> 1
b) print "2"
c) current -> 5/*right of 2 */ and go to step 3
Step 3 pushes 5 to stack and makes current NULL
Stack S -> 5, 1
current = NULL
Step 4 pops from S
a) Pop 5: Stack S -> 1
b) print "5"
c) current = NULL /*right of 5 */ and go to step 3
Since current is NULL step 3 doesn't do anything
Step 4 pops again.
a) Pop 1: Stack S -> NULL
b) print "1"
c) current -> 3 /*right of 5 */
Step 3 pushes 3 to stack and makes current NULL
Stack S -> 3
current = NULL
Step 4 pops from S
a) Pop 3: Stack S -> NULL
b) print "3"
c) current = NULL /*right of 3 */
Traversal is done now as stack S is empty and current is NULL.
13 http://coursehunt.net/
13: Printing binary tree level by level:
Level order traversal of the above tree is 1 2 3 4 5
Algorithm:
/*Function to print level order traversal of tree*/
printLevelorder(tree)
for d = 1 to height(tree)
printGivenLevel(tree, d);
/*Function to print all nodes at a given level*/
printGivenLevel(tree, level)
if tree is NULL then return;
if level is 1, then
print(tree->data);
else if level greater than 1, then
printGivenLevel(tree->left, level-1);
printGivenLevel(tree->right, level-1);
Time Complexity: ​O(n^2) in worst case
14 http://coursehunt.net/
14: Reverse level order traversal of binary tree
Reverse Level order traversal of the above tree is “4 5 2 3 1”.
METHOD 1 (Recursive function to print a given level):
we have a method printGivenLevel() which prints a given level number. The only
thing we need to change is, instead of calling printGivenLevel() from first level to last level,
we call it from last level to first level.
Time Complexity: The worst case time complexity of this method is O(n^2).
METHOD 2 (Using Queue and Stack):
Use a stack to get the reverse level order. If we do normal level order traversal and
instead of printing a node, push the node to a stack and then print contents of stack, we get “5
4 3 2 1” for above example tree, but output should be “4 5 2 3 1”. So to get the correct
sequence (left to right at every level), we process children of a node in reverse order, we first
push the right subtree to stack, then left subtree.
15: Tree traversal spiral order:
For below tree, function should print 1, 2, 3, 4, 5, 6, 7.
Method 1 (Recursive):
To print the nodes in spiral order, nodes at different levels should be printed in
alternating order. An additional Boolean variable ltr is used to change printing order of levels.
15 http://coursehunt.net/
If ltr is 1 then printGivenLevel() prints nodes from left to right else from right to left. Value
of ltr is flipped in each iteration to change the order.
Function to print level order traversal of tree:
printSpiral(tree)
bool ltr = 0;
for d = 1 to height(tree)
printGivenLevel(tree, d, ltr);
ltr ~= ltr /*flip ltr*/
Function to print all nodes at a given level
printGivenLevel(tree, level, ltr)
if tree is NULL then return;
if level is 1, then
print(tree->data);
else if level greater than 1, then
if(ltr)
printGivenLevel(tree->left, level-1, ltr);
printGivenLevel(tree->right, level-1, ltr);
else
printGivenLevel(tree->right, level-1, ltr);
printGivenLevel(tree->left, level-1, ltr);

More Related Content

What's hot (20)

Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
 
data structure(tree operations)
data structure(tree operations)data structure(tree operations)
data structure(tree operations)
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
 
Binary trees
Binary treesBinary trees
Binary trees
 
Binary search trees
Binary search treesBinary search trees
Binary search trees
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
 
Binary search trees
Binary search treesBinary search trees
Binary search trees
 
Cinterviews Binarysearch Tree
Cinterviews Binarysearch TreeCinterviews Binarysearch Tree
Cinterviews Binarysearch Tree
 
Binary tree and Binary search tree
Binary tree and Binary search treeBinary tree and Binary search tree
Binary tree and Binary search tree
 
Binary tree
Binary tree Binary tree
Binary tree
 
Bst(Binary Search Tree)
Bst(Binary Search Tree)Bst(Binary Search Tree)
Bst(Binary Search Tree)
 
Lecture7 data structure(tree)
Lecture7 data structure(tree)Lecture7 data structure(tree)
Lecture7 data structure(tree)
 
Binary searchtrees
Binary searchtreesBinary searchtrees
Binary searchtrees
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
binary tree
binary treebinary tree
binary tree
 
Unit iv data structure-converted
Unit  iv data structure-convertedUnit  iv data structure-converted
Unit iv data structure-converted
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
 
Search tree,Tree and binary tree and heap tree
Search tree,Tree  and binary tree and heap treeSearch tree,Tree  and binary tree and heap tree
Search tree,Tree and binary tree and heap tree
 

Similar to Binary Tree - Algorithms

Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanDaniyal Khan
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptxskilljiolms
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structureAnusruti Mitra
 
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
TREE DATA STRUCTURE SLIDES dsa dsa .pptxTREE DATA STRUCTURE SLIDES dsa dsa .pptx
TREE DATA STRUCTURE SLIDES dsa dsa .pptxasimshahzad8611
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeZafar Ayub
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docxsowmya koneru
 
4a searching-more
4a searching-more4a searching-more
4a searching-moreShahzad Ali
 
Binary search tree
Binary search treeBinary search tree
Binary search treeSana Yameen
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeAdityaK92
 
Part 1 Your tasks for this assignment are the following1. Disc.docx
Part 1 Your tasks for this assignment are the following1. Disc.docxPart 1 Your tasks for this assignment are the following1. Disc.docx
Part 1 Your tasks for this assignment are the following1. Disc.docxherbertwilson5999
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures treemaamir farooq
 
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11sumitbardhan
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Treesagar yadav
 
(a) There are three ways to traverse a binary tree pre-order, in-or.docx
(a) There are three ways to traverse a binary tree pre-order, in-or.docx(a) There are three ways to traverse a binary tree pre-order, in-or.docx
(a) There are three ways to traverse a binary tree pre-order, in-or.docxajoy21
 
Chapter 5_Trees.pdf
Chapter 5_Trees.pdfChapter 5_Trees.pdf
Chapter 5_Trees.pdfssuser50179b
 

Similar to Binary Tree - Algorithms (20)

Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptx
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
TREE DATA STRUCTURE SLIDES dsa dsa .pptxTREE DATA STRUCTURE SLIDES dsa dsa .pptx
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Binary tree
Binary treeBinary tree
Binary tree
 
Tree
TreeTree
Tree
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docx
 
4a searching-more
4a searching-more4a searching-more
4a searching-more
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Part 1 Your tasks for this assignment are the following1. Disc.docx
Part 1 Your tasks for this assignment are the following1. Disc.docxPart 1 Your tasks for this assignment are the following1. Disc.docx
Part 1 Your tasks for this assignment are the following1. Disc.docx
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
L 17 ct1120
L 17 ct1120L 17 ct1120
L 17 ct1120
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures tree
 
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
(a) There are three ways to traverse a binary tree pre-order, in-or.docx
(a) There are three ways to traverse a binary tree pre-order, in-or.docx(a) There are three ways to traverse a binary tree pre-order, in-or.docx
(a) There are three ways to traverse a binary tree pre-order, in-or.docx
 
Chapter 5_Trees.pdf
Chapter 5_Trees.pdfChapter 5_Trees.pdf
Chapter 5_Trees.pdf
 

Recently uploaded

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 

Recently uploaded (20)

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 

Binary Tree - Algorithms

  • 1. 1 http://coursehunt.net/ Data Structures​. 1: A Tree Is Typically Traversed In Two Ways​: A)​ ​Breadth First Traversal​:- This traversal visits nodes by levels from top to bottom and from left to right. B) Depth-First Traversal: There are three different types of depth-first traversals: PreOrder traversal​ - visit the parent first and then left and right children. InOrder traversal​ - visit the left child, then the parent and the right child. PostOrder traversal​ - visit left child, then the right child and then the parent. Breadth-First Traversal: This traversal visits nodes by levels from top to bottom and from left to right. PreOrder - 8, 5, 9, 7, 1, 12, 2, 4, 11, 3 InOrder - 9, 5, 1, 7, 2, 12, 8, 4, 3, 11 PostOrder - 9, 1, 2, 12, 7, 5, 3, 11, 4, 8 LevelOrder - 8, 5, 4, 9, 7, 11, 1, 12, 3, 2 In Below picture, we demonstrate the order of node visitation. Number 1 denotes the first node in a particular traversal and 7 denote the last node.
  • 2. 2 http://coursehunt.net/ Depth-First Traversal: There are three different types of depth-first traversals, : ● PreOrder traversal - visit the parent first and then left and right children; ● InOrder traversal - visit the left child, then the parent and the right child; ● PostOrder traversal - visit left child, then the right child and then the parent; 2: Searching Into a Binary Tree: If we want to search for a node whose key is K, start searching from the root of the binary search tree. If the root is NULL, the search contains no nodes and the search is unsuccessful. Otherwise, compare k with the key in root. If k equals the root's key, then search is successful. If k is less than root's key, then no element in the right sub tree can have a key value equal to k, therefore we search the left sub tree of a root. If k is larger than root's key value, search the right subtree of the root. Pseudocode for recursive search of a binary search​ ​tree​: element *search(treePointer root, int key) { if(!root) return NULL; if(k==root->data.key) return &(root->data); if(k<root->data.key) return search(root->leftchild, k); return search(root->rightchild, k); }
  • 3. 3 http://coursehunt.net/ 3: ​Inserting into a binary search tree: ● Check whether root node is present or not(tree available or not). If root is NULL, create root node. ● If the element to be inserted is less than the element present in the root node, traverse the left sub-tree recursively until we reach T->left/T->right is NULL and place the new node at T->left(key in new node < key in T)/T->right (key in new node > key in T). ● If the element to be inserted is greater than the element present in root node, traverse the right sub-tree recursively until we reach T->left/T->right is NULL and place the new node at T->left/T->right. Pseudocode: TreeNode insert(int data, TreeNode T) { if T is NULL { T = (TreeNode *)malloc(sizeof (Struct TreeNode)); (Allocate Memory of new node and load the data into it) T->data = data; T->left = NULL; T->right = NULL; } else if T is less than T->left { T->left = insert(data, T->left); (Then node needs to be inserted in left sub-tree.So, recursively traverse left sub-tree to find the place where the new node needs to be inserted) } else if T is greater than T->right { T->right = insert(data, T->right); (Then node needs to be inserted in right sub-tree So, recursively traverse right sub-tree to find the place where the new node needs to be inserted.) } return T; }
  • 4. 4 http://coursehunt.net/ 4: Checking if two binary trees are same: ● Two trees are identical when they have same data and arrangement of data is also same. Pseudocode: sameTree(tree1, tree2) 1. If both trees are empty then return 1. 2. Else If both trees are non -empty (a) Check data of the root nodes (tree1->data == tree2->data) (b) Check left subtrees recursively i.e., call sameTree( tree1->left_subtree, tree2->left_subtree) (c) Check right subtrees recursively i.e., call sameTree( tree1->right_subtree, tree2->right_subtree) (d) If a,b and c are true then return 1. 3 Else return 0 (one is empty and other is not) Time Complexity: Complexity of the identicalTree() will be according to the tree with lesser number of nodes. Let number of nodes in two trees be m and n then complexity of sameTree() is O(m) where m < n 5: Find size of binary tree: ● Start from the root. ● Size = 1 (for the root) + Size Of left Sub-Tree + Size Of right Sub-Tree ● solve the left sub-tree and right sub-tree recursively​. ● Size of a tree = Size of left subtree + 1 + Size of right subtree
  • 5. 5 http://coursehunt.net/ 6: Find height of binary tree: ● Get the height of left sub tree, say leftHeight ● Get the height of right sub tree, say rightHeight ● Take the Max(leftHeight, rightHeight) and add 1 for the root and return ● Call recursively.
  • 6. 6 http://coursehunt.net/ 7: Root to leaf sum of Binary tree:
  • 7. 7 http://coursehunt.net/ ● Given a binary tree and a number, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals the given number. Return false if no such path can be found. Ex: in the above tree root to leaf paths exist with following sums. 21 –> 10 – 8 – 3 23 –> 10 – 8 – 5 14 –> 10 – 2 – 2 So the returned value should be true only for numbers 21, 23 and 14. For any other number, returned value should be false. Algorithm: Recursively check if left or right child has path sum equal to ( number – value at current node) 8: Check if binary tree is a binary search tree: A binary search tree (BST) is a node based binary tree data structure which has the following properties. • The left subtree of a node contains only nodes with keys less than the node’s key. • The right subtree of a node contains only nodes with keys greater than the node’s key. • Both the left and right subtrees must also be binary search trees. From the above properties it naturally follows that: • Each node (item in the tree) has a distinct key​. Pseudocode:
  • 8. 8 http://coursehunt.net/ /* Returns true if the given tree is a binary search tree (efficient version). */ int isBST(struct node* node) { return(isBSTUtil(node, INT_MIN, INT_MAX)); } /* Returns true if the given tree is a BST and its values are >= min and <= max. */ int isBSTUtil(struct node* node, int min, int max) 9: Level order traversal of binary tree: Level order traversal of the above tree is 1 2 3 4 5 Algorithm: /*Function to print level order traversal of tree*/ printLevelorder(tree) for d = 1 to height(tree) printGivenLevel(tree, d); /*Function to print all nodes at a given level*/ printGivenLevel(tree, level) if tree is NULL then return; if level is 1, then print(tree->data); else if level greater than 1, then printGivenLevel(tree->left, level-1); printGivenLevel(tree->right, level-1); METHOD 2 (Use Queue): For each node, first the node is visited and then it’s child nodes are put in a FIFO queue. printLevelorder(tree) 1) Create an empty queue q 2) temp_node = root /*start from root*/ 3) Loop while temp_node is not NULL a) print temp_node->data. b) Enqueue temp_node’s children (first left then right children) to q c) Dequeue a node from q and assign it’s value to temp_node
  • 9. 9 http://coursehunt.net/ 10: Iterative PostOrder traversal of binary tree: The key to to iterative postorder traversal is the following: 1. The order of "Postorder" is: left child -> right child -> parent node. 2. Find the relation between the previously visited node and the current node 3. Use a stack to track nodes As we go down the tree to the left, check the previously visited node. If the current node is the left or right child of the previous node, then keep going down the tree, and add left/right node to stack when applicable. When there are no children for current node, i.e., the current node is a leaf, pop it from the stack. Then the previous node become to be under the current node for next loop Ex: 1. Push 1 to first stack. First stack: 1 Second stack: Empty 2. Pop 1 from first stack and push it to second stack. Push left and right children of 1 to first stack First stack: 2, 3 Second stack: 1 3. Pop 3 from first stack and push it to second stack. Push left and right children of 3 to first stack First stack: 2, 6, 7 Second stack:1, 3 4. Pop 7 from first stack and push it to second stack. First stack: 2, 6 Second stack:1, 3, 7 5. Pop 6 from first stack and push it to second stack. First stack: 2 Second stack:1, 3, 7, 6 6. Pop 2 from first stack and push it to second stack.
  • 10. 10 http://coursehunt.net/ Push left and right children of 2 to first stack First stack: 4, 5 Second stack:1, 3, 7, 6, 2 7. Pop 5 from first stack and push it to second stack. First stack: 4 Second stack: 1, 3, 7, 6, 2, 5 8. Pop 4 from first stack and push it to second stack. First stack: Empty Second stack: 1, 3, 7, 6, 2, 5, 4 The algorithm stops since there is no more item in first stack. Observe that content of second stack is in postorder fashion. Print them. 11: Iterative Preorder traversal of binary tree: 1. Create a Stack. 2. Print the root and push it to Stack and go left i.e root=root.left and till it hits the NULL. 3. If root is null and Stack is empty Then 1. return, we are done. 4. Else 1. Pop the top Node from the Stack and set it as, root = popped_Node. 2. Go right, root = root.right. 3. Go to step 2. 5. End If Code: public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }
  • 11. 11 http://coursehunt.net/ } public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> returnList = new ArrayList<Integer>(); if(root == null) return returnList; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while(!stack.empty()){ TreeNode n = stack.pop(); returnList.add(n.val); if(n.right != null){ stack.push(n.right); } if(n.left != null){ stack.push(n.left); } } return returnList; } } 12: Iterative Inorder traversal of binary tree: Create an empty stack S. 2) Initialize current node as root 3) Push the current node to S and set current = current->left until current is NULL 4) If current is NULL and stack is not empty then a) Pop the top item from stack. b) Print the popped item, set current = popped_item->right c) Go to step 3. 5) If current is NULL and stack is empty then we are done. Ex: 1 / 2 3 / 4 5 Step 1 Creates an empty stack: S = NULL Step 2 sets current as address of root: current -> 1
  • 12. 12 http://coursehunt.net/ Step 3 Pushes the current node and set current = current->left until current is NULL current -> 1 push 1: Stack S -> 1 current -> 2 push 2: Stack S -> 2, 1 current -> 4 push 4: Stack S -> 4, 2, 1 current = NULL Step 4 pops from S a) Pop 4: Stack S -> 2, 1 b) print "4" c) current = NULL /*right of 4 */ and go to step 3 Since current is NULL step 3 doesn't do anything. Step 4 pops again. a) Pop 2: Stack S -> 1 b) print "2" c) current -> 5/*right of 2 */ and go to step 3 Step 3 pushes 5 to stack and makes current NULL Stack S -> 5, 1 current = NULL Step 4 pops from S a) Pop 5: Stack S -> 1 b) print "5" c) current = NULL /*right of 5 */ and go to step 3 Since current is NULL step 3 doesn't do anything Step 4 pops again. a) Pop 1: Stack S -> NULL b) print "1" c) current -> 3 /*right of 5 */ Step 3 pushes 3 to stack and makes current NULL Stack S -> 3 current = NULL Step 4 pops from S a) Pop 3: Stack S -> NULL b) print "3" c) current = NULL /*right of 3 */ Traversal is done now as stack S is empty and current is NULL.
  • 13. 13 http://coursehunt.net/ 13: Printing binary tree level by level: Level order traversal of the above tree is 1 2 3 4 5 Algorithm: /*Function to print level order traversal of tree*/ printLevelorder(tree) for d = 1 to height(tree) printGivenLevel(tree, d); /*Function to print all nodes at a given level*/ printGivenLevel(tree, level) if tree is NULL then return; if level is 1, then print(tree->data); else if level greater than 1, then printGivenLevel(tree->left, level-1); printGivenLevel(tree->right, level-1); Time Complexity: ​O(n^2) in worst case
  • 14. 14 http://coursehunt.net/ 14: Reverse level order traversal of binary tree Reverse Level order traversal of the above tree is “4 5 2 3 1”. METHOD 1 (Recursive function to print a given level): we have a method printGivenLevel() which prints a given level number. The only thing we need to change is, instead of calling printGivenLevel() from first level to last level, we call it from last level to first level. Time Complexity: The worst case time complexity of this method is O(n^2). METHOD 2 (Using Queue and Stack): Use a stack to get the reverse level order. If we do normal level order traversal and instead of printing a node, push the node to a stack and then print contents of stack, we get “5 4 3 2 1” for above example tree, but output should be “4 5 2 3 1”. So to get the correct sequence (left to right at every level), we process children of a node in reverse order, we first push the right subtree to stack, then left subtree. 15: Tree traversal spiral order: For below tree, function should print 1, 2, 3, 4, 5, 6, 7. Method 1 (Recursive): To print the nodes in spiral order, nodes at different levels should be printed in alternating order. An additional Boolean variable ltr is used to change printing order of levels.
  • 15. 15 http://coursehunt.net/ If ltr is 1 then printGivenLevel() prints nodes from left to right else from right to left. Value of ltr is flipped in each iteration to change the order. Function to print level order traversal of tree: printSpiral(tree) bool ltr = 0; for d = 1 to height(tree) printGivenLevel(tree, d, ltr); ltr ~= ltr /*flip ltr*/ Function to print all nodes at a given level printGivenLevel(tree, level, ltr) if tree is NULL then return; if level is 1, then print(tree->data); else if level greater than 1, then if(ltr) printGivenLevel(tree->left, level-1, ltr); printGivenLevel(tree->right, level-1, ltr); else printGivenLevel(tree->right, level-1, ltr); printGivenLevel(tree->left, level-1, ltr);