SlideShare a Scribd company logo
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

Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
Muhazzab Chouhadry
 
data structure(tree operations)
data structure(tree operations)data structure(tree operations)
data structure(tree operations)
Waheed Khalid
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
Katang Isip
 
Binary trees
Binary treesBinary trees
Binary trees
Simratpreet Singh
 
Binary search trees
Binary search treesBinary search trees
Binary search trees
Dhananjaysinh Jhala
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
shameen khan
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
Trupti Agrawal
 
Binary search trees
Binary search treesBinary search trees
Binary search trees
Dwight Sabio
 
Cinterviews Binarysearch Tree
Cinterviews Binarysearch TreeCinterviews Binarysearch Tree
Cinterviews Binarysearch Tree
cinterviews
 
Binary tree and Binary search tree
Binary tree and Binary search treeBinary tree and Binary search tree
Binary tree and Binary search tree
Mayeesha Samiha
 
Binary tree
Binary tree Binary tree
Binary tree
Rajendran
 
Bst(Binary Search Tree)
Bst(Binary Search Tree)Bst(Binary Search Tree)
Bst(Binary Search Tree)
Eleti Ganapathi
 
Lecture7 data structure(tree)
Lecture7 data structure(tree)Lecture7 data structure(tree)
Binary searchtrees
Binary searchtreesBinary searchtrees
Binary searchtrees
HasnainBaloch12
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
Abhishek L.R
 
binary tree
binary treebinary tree
binary tree
Shankar Bishnoi
 
Unit iv data structure-converted
Unit  iv data structure-convertedUnit  iv data structure-converted
Unit iv data structure-converted
Shri Shankaracharya College, Bhilai,Junwani
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
Saurabh Mishra
 
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
ManishPrajapati78
 
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
zia eagle
 

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 Khan
Daniyal Khan
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptx
skilljiolms
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
Anusruti 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 .pptx
asimshahzad8611
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
Zafar Ayub
 
Binary tree
Binary treeBinary tree
Binary tree
Afaq Mansoor Khan
 
Tree
TreeTree
Tree
bhumish
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docx
sowmya koneru
 
4a searching-more
4a searching-more4a searching-more
4a searching-more
Shahzad Ali
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
Sana Yameen
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
AdityaK92
 
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
herbertwilson5999
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
VijayaLakshmi506
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
worldchannel
 
L 17 ct1120
L 17 ct1120L 17 ct1120
L 17 ct1120
Zia Ush Shamszaman
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures tree
maamir 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-11
sumitbardhan
 
Trees second part in data structures with examples
Trees second part in data structures with examplesTrees second part in data structures with examples
Trees second part in data structures with examples
rupanaveen24
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
sagar 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.docx
ajoy21
 

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
 
Trees second part in data structures with examples
Trees second part in data structures with examplesTrees second part in data structures with examples
Trees second part in data structures with examples
 
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
 

Recently uploaded

Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 

Recently uploaded (20)

Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 

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);