Find the maximum element in a binary tree

I am really confused about finding an item in binary tree.

Question . When we say we are looking for an element in a binary tree, the maximum in this case, suppose the tree is sorted ???
If not, look at the code below, I got it from a book, and almost every online address offers a similar pattern

int FindMaxNmb(BinaryTreeNode root)
    {
        int root_val,left,right,max;
        if(root!=null)
        {
            root_val = root.getData();

            //recursion - this is what i dont understand

            /*
             *
             * This code would have made sense if binary tree contained
             * sorted elements,like  The left subtree of a node contained 
             * only nodes with keys less than the node key The right subtree 
             * of a node contained only nodes with keys greater 
             * than the node key.
             *   
             * */
            left = FindMaxNmb(root.getLeft());
            right = FindMaxNmb(root.getRight());

            //Find max nmbr
            if(left > right)
            {
                max = left;
            }
            else
            {
                max = right;
            }

            if(root_val > max)
            {
                max = root_val;
            }
        }
        return max;
    }

What I do not understand: take this recusrion for example left = FindMaxNmb(root.getLeft());it will continue until it reaches the leftmost bottom sheet and then assigns a value, the same with getRight().... but this thing only works for the left node, which has 2 children ... how to do this checks the value of the remaining nodes (I assume that the binary tree is not sorted)

, - ... , !!

+4
1

Binary Tree , BST node - BT .

, . ( BST, " " node , .)

BT , node ( node ), .

, , BST ( ):

http://upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Binary_tree.svg/192px-Binary_tree.svg.png

, , , - , node.

-2
--7 (l)
---2 (l)
---6 (r)
----5 (l)
----11 (r)
--5 (r)
---9 (r)
----4 (l)

"", - ( FindMaxNmb).

.

  • .. node 11, node, 6
  • ( 6), 7
  • ( 7), 2
  • ( 2), (5)..
+2

Source: https://habr.com/ru/post/1525909/


All Articles