1

The characteristic of the binary search tree is that the value of any node:

  • Are greater than any node in the left subtree.
  • Are smaller than any node in the right subtree.

Because of the characteristics of binary search trees, we can apply algorithms more efficiently.

intensive reading

Remember "Algorithm-Binary Tree" mentioned binary tree problem? If this is a binary search tree, is there a more clever solution? You can pause and think first.

Nearest common ancestor of binary search tree

The nearest common ancestor of a binary search tree is a simple problem, the topic is as follows:

Given a binary search tree, find the nearest common ancestor of two specified nodes in the tree.

Baidu Encyclopedia recent common ancestor is defined as follows: "For the rooted tree T two nodes p , q , recent common ancestor is represented as a node x , meet x is p , q ancestors and x depth as large as possible (A node can also be its own ancestor)."

The first judgment condition is the same, that is, the current node value is equal to p or q , then the current node is its nearest common ancestor.

If not? Considering the characteristics of the binary search tree and the common ancestor at the same time, we can find:

  1. If the p q are located on the left or right of the current node, the current node meets the requirements.
  2. If p q is greater than the current node, and the other is smaller than the current node, it means that p q distributed on the left and right sides of the current node.

Based on the above considerations, it can be judged only by the value, so the problem is simplified.

Next, look at an introductory question, that is, how to verify that a binary tree is a binary search tree.

Verify the binary search tree

Verifying the binary search tree is a middle-level problem, the topic is as follows:

Given a binary tree, judge whether it is a valid binary search tree.

Suppose a binary search tree has the following characteristics:

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

This problem seems to be implemented with very elegant recursion.

The most important thing about the binary search tree is the restriction on the value of the node. If we can correctly hold the value of each node, we can judge.

How to judge whether the node value is correct? We can use a recursive way to reverse, that is, starting from the root node, assuming the root node value is x , then the value of the left tree node must be less than x , and then to the left, then the value will be less than (assuming the first left node value x1 ) x1 , the right tree is the same judgment, so you can write the answer:

function isValidBST(node: TreeNode, min = -Infinity, max = Infinity) {
  if (node === null) return true
  // 判断值范围是否合理
  if (node.val < min || node.val > max) return false
  // 继续递归,并且根据二叉搜索树特定,进一步缩小最大、最小值的锁定范围
  return 
    // 左子树值 max 为当前节点值
    isValidBST(node.left, min, node.val) &&
    // 右子树值 min 为当前节点值
    isValidBST(node.right, node.val, max) &&
}

Next, let's look at some simple binary search tree operation problems, such as deleting nodes in the binary search tree.

Delete the node in the binary search tree

Deleting a node in a binary search tree is a middle-level problem, the topic is as follows:

Given the root node root of a binary search tree and a value key, delete the node corresponding to the key in the binary search tree, and ensure that the nature of the binary search tree remains unchanged. Returns a reference to the root node of the binary search tree (which may be updated).

Generally speaking, deleting a node can be divided into two steps:

  1. First find the node that needs to be deleted;
  2. If it is found, delete it.

Explanation: The time complexity of the algorithm is required to be O(h) , and h is the height of the tree.

To delete the node of the binary search tree, it is not difficult to find the node itself, because if the value is small, it is found from the left subtree; if the value is large, it is found from the right subtree, which itself is very simple to find. The difficulty lies in how to ensure that after deleting elements, this tree is still a binary search tree?

Suppose we delete leaf nodes. Obviously, any subtree of the binary search tree is a binary search tree, and we have not destroyed the relationship of other nodes, so we can delete it directly, which is the easiest.

If the deleted node is not a leaf node, then who will "upper" replace this node? The complexity of the problem is O(h) Obviously, it cannot be reconstructed. We need to consider it carefully.

Assuming that the deleted node has a right node, then a replacement value must be found from the right node and moved up. Whom should I look for? Find the minimum value of the right node. The minimum value is easy to find. After finding the replacement, the is transferred to delete this minimum node, and the recursion is over.

Assuming that the deleted node has a left node, but there is no right node, then find the largest replacement from the left node, and delete the found node recursively in the same way.

It can be seen that to delete the binary search tree, in order to keep the nature of the binary search tree unchanged, it is necessary to continuously delete nodes recursively for repeated sub-problems.

After you master the characteristics of the binary search tree, you can try to construct a binary search tree. The following is a question that allows you to construct a binary search tree arbitrarily: different binary search trees.

Different binary search trees

Different binary search trees are a middle-level problem, the topic is as follows:

Give you an integer n , find out how many kinds of binary search trees n nodes and the node values are different from 1 to n Returns the number of binary search trees that satisfy the meaning of the question.

This question focuses on the combination of dynamic programming thinking + Cartesian product thinking.

Need to imagine all the possibilities as after the root node is determined, how many combinations of left and right subtrees are there?

For example, suppose n=10 , then these 10 nodes, suppose I take the third node as the root node, then the left subtree has 2 nodes, and the right subtree has 7 nodes. This combination has as many as DP(2) * DP(7) , Suppose DP(n) represents the number of n nodes that can form any binary search tree.

This is only the case where the third node is the root node. In fact, each node is a different tree as the root node (axisymmetric is also different), then we have to calculate from the first node to the n node .

So the answer comes out, we first consider the special case DP(0)=1 DP(1)=1 , so:

function numTrees(n: number) {
  const dp: number[] = [1, 1]

  for (let i = 2; i <= n; i++) {
    for (let j = 1; j <= i; j++) {
      dp[i] += dp[j - 1] * dp[i - j]
    }
  }

  return dp[n]
}

Finally, look at a value-finding question, not to find the maximum value, but to find the k-th largest value.

The Kth largest node of the binary search tree

The Kth largest node of the binary search tree is a simple problem, the topic is as follows:

Given a binary search tree, please find the node k

The reason why this question is simple is that the middle-order traversal of the binary search tree is from small to large, so as long as the middle-order traversal is k , the node with the largest number 060f514f46bc59 can be found.

Reverse order middle order traversal, namely right, root, left.

This problem is solved.

to sum up

The feature of binary search tree is very simple, that is, the root node value is sandwiched between the left and right subtrees. Using this feature can solve almost all related problems.

But through the above examples, it can be found that it is not enough to be familiar with the characteristics of binary search trees. Some problems need to be solved by combining general algorithm ideas such as binary tree in-order traversal and common ancestor features. Therefore, it is important to learn to understand.

The discussion address is: Intensive Reading "Algorithm-Binary Search Tree" · Issue #337 · dt-fe/weekly

If you want to participate in the discussion, please click here , there are new topics every week, weekends or Mondays. Front-end intensive reading-to help you filter reliable content.

Follow front-end intensive reading WeChat public

<img width=200 src="https://img.alicdn.com/tfs/TB165W0MCzqK1RjSZFLXXcn2XXa-258-258.jpg">

Copyright notice: Freely reprinted-non-commercial-non-derivative-keep the signature ( Creative Commons 3.0 License )

黄子毅
7k 声望9.5k 粉丝