[B] [C] [D]
Implement a function that checks if a binary tree is a binary search tree.
Example 1:
Input: 2 / \ 1 3 Output: trueCopy the code
Example 2:
Input: 5 / \ 1 4 / \ 3 6 Output: false Description: Input: [5,1,4, NULL, NULL,3,6] The root node has a value of 5, but its right child node has a value of 4.Copy the code
Their thinking
Properties of binary search tree: For any subtree, the value of the root node is greater than that of the left child node, and the value of the root node is less than that of the right child node
Based on the above properties of binary search tree, if a sequence of binary search tree traversal, it will be a strict ascending sequence, so that we can be in order to input binary tree traversal, if found in the process of traversing the nature of the node value violated the strict ascending, shows the current binary tree is not a binary search tree.
Code implementation
Var isValidBST = function(root) {let pre = null,res = true; Function inorder(node){if(node === null) return; inorder(node.left); If (pre === null) pre = node.val else{// If pre is less than the current node value, Pre if(pre<node.val) pre = node.val else{// If (pre<node.val) return; } } inorder(node.right); } inorder(root); Return res; };Copy the code
Here we have leetcode- interview question 04.05- legal binary search tree
If you have any questions or suggestions, please leave a comment!