Hot interview questions (verify binary search tree)

Given the root node of a binary tree  root , determine whether it is a valid binary search tree.

A valid  binary search tree is defined as follows:

  • A node's left subtree contains only numbers  less than  the current node.
  • The right subtree of a node contains only  numbers greater than  the current node.
  • All left and right subtrees must themselves be binary trees

       The binary tree satisfies the above three conditions. Some students will say, isn't BST just big on the left and small on the right? Shouldn't I just judge root.val>root.left.val and root.val<root.right.val ?

         This is definitely wrong, because the characteristic of BST left small and right large means that root.val is larger than all nodes in the left subtree and smaller than all nodes in the right subtree, so just check whether the two nodes are If it is not enough, we can use auxiliary functions to increase the list of function parameters, carry additional information in the parameters, and pass on the reasonable value range of the next node for judgment

Because the root node has no range limit at the beginning, so our boundary can be infinite at its minimum and infinite at its maximum

isValidBST(root,Integer.MIN_VALUE,Integer.MAX_VALUE);

If the current node does not meet the legal boundary, directly return false

 if(node.val<=lower||node.val>=upper){
            return false;
        }

To traverse the left subtree and right subtree of the current node, and update the value range

isValidBST(node.left,lower,node.val)&&isValidBST(node.right,node.val,upper);

result:

       When I saw the test case, I was suddenly enlightened. When I saw this relatively large number, I saw that it was a numerical type problem, which was out of range. Then we changed the Integer to a larger Long, and then:

 

Guess you like

Origin blog.csdn.net/dfdbb6b/article/details/132261567