Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel...

25
Tutorial 4: Search Trees Algorithms - 1 ( CS21003)

Transcript of Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel...

Page 1: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Tutorial 4: Search Trees

Algorithms - 1 ( CS21003)

Page 2: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Problem - 1

Page 3: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Problem-1

You are given a rooted tree T. The width of T is the maximum number of nodes at a level in the tree. For example, consider a tree of height three on ten nodes a, b, c, d, e, f, g, h, i, j, where a is the root having three children b, c, d, node b has two children e, f, node d has three children g, h, i, and h has one child j. In this tree, the numbers of nodes at levels 0, 1, 2, 3 are respectively 1, 3, 5, 1. The width of this tree is therefore 5. Design an algorithm to compute the width of T in O(n) time, where n is the number of nodes in T.

Page 4: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Hint 1

Draw the tree.

Problem Statement: You are given a rooted tree T. The width of T is the maximum number of nodes at a level in the tree. For example, consider a tree of height three on ten nodes a, b, c, d, e, f, g, h, i, j, where a is the root having three children b, c, d, node b has two children e, f, node d has three children g, h, i, and h has one child j. In this tree, the numbers of nodes at levels 0, 1, 2, 3 are respectively 1, 3, 5, 1. The width of this tree is therefore 5. Design an algorithm to compute the width of T in O(n) time, where n is the number of nodes in T.

Page 5: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Hint 2

Solve for the simpler case when it is a binary tree, you may use O(h) space to maintain the number of nodes at each level in the binary tree.

We use an array C of size h+ 1 in order to store the counts of the nodes at different levels of T. This array is filled by a recursive traversal of the tree. Then, a maximum is taken over the counts.

Page 6: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Solutionvoid traverse ( tree T, int C[], int level ) {if (T == NULL) return;C[level]++;traverse(T -> left, C, level+1);

traverse(T -> right, C, level);}int width ( tree T ){int *C, max, h, i;h = height(T);C = (int *)malloc((h+1) * sizeof(int));for (i=0; i<=h; ++i) C[i] = 0;traverse(T,C,0);max = 0;for (i=0; i<=h; ++i) if (C[i] > max) max = C[i];free(C);return max;}

Page 7: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Problem - 2

Page 8: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Problem -2

Assume that a set S of n numbers is stored in some form of balanced binary search tree, i.e., the height of the tree is O(logn). In addition to the key value and the pointers to children, assume that every node contains the number of nodes in its subtree. Design O(logn) algorithms for performing the following operation:

Given a positive integer k, 1 ≤ k ≤ n, compute the kth smallest element of S.

Page 9: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Hint 1

The idea is to use the elements in the left subtree recursively. Let l be the number of elements in the left subtree (can be queried in O(1) time). if k = l + 1, root is the answer, if k < l, search should proceed in the left subtree, if k > l + 1, search should proceed in the right subtree for finding k −l−1th smallest element.

Page 10: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Solution

start:

if K = root.leftElement + 1

root node is the K th node.

goto stop

else if K > root.leftElements

K = K - (root.leftElements + 1)

root = root.right

goto start

else

root = root.left

goto start

stop:

Page 11: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Problem - 3

Page 12: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Problem - 3

Given a complete binary tree with N nodes and each node have a distinct integer a

i attached with it, find the minimum number of

swaps you can make to convert the binary tree into binary search tree. In one swap, you can select any two nodes and swap their values.

You will be given the array representation of the binary tree. Root of the tree will be at a

1 . Left child of root will be at a

2 and right child of

root will be at a3

. Left child of node at array position k will be at a2*k

and right child of node at array position k will be at a

2*k+1 .

Page 13: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Contd.

Input:

1) an integer, N , denoting the number of nodes.2) N space separated integers, denoting the value attached to ith

node.

Output:

1) a single integer, denoting the minimum number of swaps needed to convert binary tree into a binary search tree.

Page 14: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Hint 1

Sample Input:

3

1 2 3

Sample Output: 1

The idea is to use the fact that inorder traversal of Binary Search Tree is in increasing order of their value.

Page 15: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Hint 2

Input: 7

5, 6, 7, 8, 9, 10, 11

Output: 3

Idea: find the inorder traversal of the Binary Tree and store it in the array and try to sort the array. The minimum number of swap required to get the array sorted will be the answer.

Page 16: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Solution

int minSwaps(std::vector<int> &v) { std::vector<pair<int,int> > t(v.size()); int ans = 0; for(int i = 0; i < v.size(); i++) t[i].first = v[i], t[i].second = i; sort(t.begin(), t.end()); for(int i = 0; i < t.size(); i++) { // second element is equal to i if(i == t[i].second) continue; else { // swaping of elements swap(t[i].first, t[t[i].second].first); swap(t[i].second, t[t[i].second].second); }

// Second is not equal to i if(i != t[i].second) --i; ans++; } return ans; }

#==============================int main() { int a[] = { 5, 6, 7, 8, 9, 10, 11 }; int n = sizeof(a) / sizeof(a[0]); std::vector<int> v; inorder(a, v, n, 0); #Write inorder traversal cout << minSwaps(v) << endl; }

Page 17: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Problem - 4

Page 18: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Problem - 4

Write a function inorderSuccessor(T,x) to return the node (a pointer to the node, to be more precise) in T, that stores the immediate successor of the key x. If T does not store x, or if x is the largest key stored in T, this successor does not exist (return NULL in these cases). Otherwise, the node stores the smallest key larger than x. Please implement without using Parent pointer

Page 19: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Hint 1

In the diagram, inorder successor of 8 is 10, inorder successor of 10 is 12 and inorder successor of 14 is 20

Clue: In Binary Search Tree, Inorder Successor of an input node can also be defined as the node with the smallest key greater than the key of input node. So, it is sometimes important to find next node in sorted order.

Page 20: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Solutionstruct node * inOrderSuccessor(struct node *root, struct node *n) { if( n->right != NULL ) return minValue(n->right); struct node *succ = NULL; // Start from root and search for successor down the tree while (root != NULL) { if (n->data < root->data) { succ = root; root = root->left; } else if (n->data > root->data) root = root->right; else break; } return succ; }

Time Complexity: O(h) where h is height of tree.

Page 21: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Problem - 5

Page 22: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Problem- 5Monk has an array A having N distinct integers and a Binary Search Tree which is initially empty. He inserts all the elements of the array from index 1 to N in the BST in the order given in the array. But wait! The tree so formed turns out to be cursed. Monk is having some weird experiences since he made that tree.So, now to stop all that, Monk has two options, to destroy the BST or to pray to God and ask for a solution. Now since Monk has to use this BST in a Code Monk Challenge, he cannot destroy it. So he prays to God.God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values, X and Y, present in the BST and ask him to find the maximum value that lie in the path between node having value X and node having value Y. (including X and Y ).

Now since, Monk is very afraid of that tree he asks for your help.

Page 23: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Hint -1

Input: array A andtwo space separated integers denoting X and Y.

Path between node having value 3 and node having value 7 is 3 -> 4 -> 7. Maximum value that lies on this path is 7.

Page 24: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Solutionint getMax(node* root, int mn, int mx){ if(root!=NULL) { if(root->data>mx) { return getMax(root->left,mn,mx); } else if(root->data<mn) { return getMax(root->right,mn,mx); } else { int mxm=0; node* temp=root; mxm=root->data; while(temp!=NULL && temp->data!=mx) {

if(temp->data>mx) { if(mxm<temp->data) mxm=temp->data; temp=temp->left; } else { temp=temp->right; } } if(mxm<mx) { mxm=mx; } return mxm; } }}

Page 25: Trees Tutorial 4: Searchpawang/courses/ALGO19/tut4.pdf · God answer his prayers and sends an angel named Micro. Now, Micro asks Monk to find something. He tells him two values,

Solutionint main(){ or(i=0;i<n;i++) { scanf("%d",&arr[i]); root=insertNode(root,arr[i]); #inserting node in tree } int a,b; scanf("%d %d",&a,&b);

int mn=(a<b?a:b);

int mx=a+b-mn; int ans=getMax(root,mn,mx); printf("%d ",ans); return 0;}