Verify binary search tree


Topic source here to verify binary search tree

Detailed definition of binary search tree

I’ll copy the title here~

Given a binary tree, judge whether it is an effective binary search tree.

Suppose a binary search tree has the following characteristics:

The left subtree of a node contains only the number less than the current node. The right subtree of a node only contains the number greater than the current node. All left and right subtrees must also be binary search trees. Example 1:

Input: 2 / ** 1 3** Output: true Example 2:

Input: 5 / ** 1 4_* **/ *_ 3 6 Output: false Explanation: the input is: [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.



Traversal binary tree, each traversal to make clear the judgment conditions on the line. Let’s first look at the various methods of traversing binary tree, because it is to judge that the nodes on the left are smaller than those on the right, which is easier to understand with middle order. The code is as follows, detailed in the comments.

 * Definition for a binary tree node.  
 * function TreeNode(val) {  
 *     this.val = val;  
 *     this.left = this.right = null;  
 * }  
 * @param {TreeNode} root  
 * @return {boolean}  
var isValidBST = function(root) {  
 //If there is only one node, it is a binary search tree  
 if(root && root.right == null && root.left == null){  
 return true;  
 //Save the omitted nodes, and then select them in order  
 var tmpStack = [];  
 //Current node, starting from top  
 var curNode = root;  
 //Previous node  
 var lastNode = null;  
 while(curNode != null || tmpStack.length != 0){  
 //Middle order traversal: starting from the far left  
 while(curNode != null){  
 //Not the leftmost? Then save it in tmpstack and use it later  
 //The left node of the current node, plus this while loop, determines whether its left is empty  
 curNode = curNode.left;  
 //This is the only way to get a null value, so you need to get the last node value that is not empty  
 curNode = tmpStack.pop();  
 //Ratio size  
 if(lastNode!==null && curNode.val <= lastNode){  
 return false;  
 //The current node is recorded as the previous node for the next comparison  
 lastNode = curNode.val;  
 //Look to the right  
 curNode = curNode.right;  
 return true;  


  1. When I think of learning data structure, binary tree learning is the best, today’s topic love love

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]