Wednesday, 15 February 2012

max - minimum element of binary tree -


I have implemented the function to find the maximum and minimum element of the binary tree. But for this I am getting the wrong output. .

The function to find maximum binary trees.

  int FindMax (struct TreeNode * bt) {// Get the maximum value of the binary tree ... int max; // Get the maximum of the left sub-tree; Int left; // Get the maximum of the right sub-tree int correct; // The root of the current node meets the root; If (bt! = Null) {root = bt-> data; // Call the left tree repeatedly .... Left = SearchMax (BT-> left child); // Call alternate on the right tree ... Right = Search Max (BT-> Right Chald); If (left and right) {max = left; } And {max = true; } If (max; rt) {max = root; }} Return max; }   

Function to find the minimum of binary trees.

  int FindMin (struct tree_node * bt) {// Get the minimum value of binary tree ... int min; // Get the minimum of left sub-tree; Int left; // Get the minimum of the right sub-tree int correct; // The root of the current node meets the root; If (bt! = Null) {root = bt-> data; // Call the left tree again .... Left = Searchman (BT-> left child); // Call the right tree in the right place ... right = searchman (bt-> right-handed); If (left & lt; right) {min = left; } Else {min = right; } If (min> root) {min = root; }} Return minutes; }   

Output: maximum 32767 tree

minimum of tree

The problem is that you allow the function to call on an empty tree. If there is a BT null, then you are going to return a uninitialized value for minimum , which seems to be 0.

I do not think how you actually discover the whole tree. O (logN) (if your tree is balanced), O (n) no. I suggest that you do not call blindly instead, instead of always follow the path that is guaranteed to reach the minimum. As soon as you search for that value, your recurrence stops:

  int FindMin (struct treeNode * bt) {if (! Bt) returns 0; // If there is nothing in the tree then, if (BT-> left child) returns Finefine (BT-> left-handed); Returns BT-> Data; }   

It is easy.

Note that I do not want to go to the right branch, because it will always be larger than the current node.

No comments:

Post a Comment