Binary search tree js

Binary search tree

Also called binary search tree, binary sort tree has the following characteristics

  • If there is a left tree, the values ​​of all nodes of the left tree are less than the value of the root node.
  • If there is a right tree, the value of all nodes of the right tree is greater than the value of the root node.
  • The left and right subtrees of any node are also binary search trees
  • If there are n elements in total, each operation takes O(logn) time on average.
  • The middle order traversal of the binary search tree is an increasing sequence
Find a node
function findNode(root, num) {
    
    
  if (root === null) {
    
    
    return null;
  } else if (num < root.val) {
    
    
    return findNode(root.left, num)
  } else if (num > root.val){
    
    
    return findNode(root.right, num)
  }else {
    
    
    return root;
  }
}
Take the maximum value
function findMaxNode(root) {
    
    
  if(root === null){
    
    
    return null;
  }else {
    
    
    if(root.right == null){
    
    
      return root;
    }else {
    
    
      return findMaxNode(root.right)
    }
  }
}

Take minimum
function findMinNode(root) {
    
    
  if(root === null){
    
    
    return null;
  }else {
    
    
    if(root.left == null){
    
    
      return root;
    }else {
    
    
      return findMinNode(root.left)
    }
  }
}
Verify Binary Search Tree
// 方法一 递归
const helper = (root, lower, upper) => {
    
    
    if (root === null) return true;
    if (root.val <= lower || root.val >= upper) return false;
    return helper(root.left, lower, root.val) && helper(root.right, root.val, upper);
  }
  var isValidBST = function(root) {
    
    
    return helper(root, -Infinity, Infinity);
  };
// 方法二 栈
var isValidBST = function(root) {
    
    
 let stack = [];
 let inorder = -Infinity;

 while (stack.length || root !== null) {
    
    
   while (root !== null) {
    
    
     stack.push(root);
     root = root.left;
   }
   root = stack.pop();
   // 如果中序遍历得到的节点的值小于等于前一个 inorder,说明不是二叉搜索树
   if (root.val <= inorder) return false;
   inorder = root.val;
   root = root.right;
 }
 return true;
};
The Kth largest node of the binary search tree
var kthLargest = function (root, k) {
    
    
    // 中序遍历
    let res = dfs(root, k);
    return res.reverse()[k - 1];
};
let res = [];
const dfs = (root) => {
    
    
    if (!root) return;
    dfs(root.left);
    res.push(root.val);
    dfs(root.right)
    return res;
}

Guess you like

Origin blog.csdn.net/qq_29334605/article/details/105968079