Binary Search Tree is defined as follows:
The left subtree of a node contains only a number smaller than the current node.
The right subtree of a node contains only a number greater than the current node.
All left and right subtrees themselves must also be binary search trees.
Brush the binary search tree again
(I)
230. The K-th smallest element in the binary search tree
230. The K-th smallest element in the binary search tree
Given the root node root of a binary search tree and an integer k, please design an algorithm to find the K smallest element (counting from 1).
- The sequence traversed in the binary search tree is an ascending sequence.
- To solve this problem, you just need to traverse the middle order and assign the k-th value to res
int res = 0; int index = 0; public int kthSmallest(TreeNode root, int k) { traverse(root, k); return res; } //Middle order traversal, assign the k-th value to res public void traverse(TreeNode root, int k){ if(root == null) return; traverse(root.left, k); index++; if(index == k){ res = root.val; return; } traverse(root.right, k); }
538. Convert binary search tree to cumulative tree
538. Convert binary search tree to cumulative tree
Give the root node of the binary search tree. The node values of the tree are different. Please convert it into a Greater Sum Tree so that the new value of each node is equal to the sum of the values greater than or equal to node.val in the original tree.
//The node value of the rightmost leaf node of the original binary search tree is the largest public TreeNode convertBST(TreeNode root) { traverse(root); return root; } int sum = 0; public void traverse(TreeNode root){ if(root == null) return; //Accumulate from the right node traverse(root.right); sum = sum + root.val; root.val = sum; traverse(root.left); return; }
(II)
98. Validate binary search tree
98. Validate binary search tree
Give you the root node of a binary tree, root, to determine whether it is an effective binary search tree.
//Each node should be greater than [?] and less than [?] public boolean isValidBST(TreeNode root) { return isTrue(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } //During the force buckle test, the test data may exceed the limit. You can change int to long public boolean isTrue(TreeNode root, int min, int max){ if(root == null) return true; if(root.val <= min || root.val >= max) return false; //The maximum value of the left subtree is the value of the current node, and the minimum value of the right subtree is the value of the current node return isTrue(root.left, min, root.value) && isTrue(root.right, root.val, max); }
700. Search in binary search tree
700. Search in binary search tree
Given the root node of the binary search tree and a value. You need to find the node whose node value is equal to the given value in the BST. Returns the subtree with this node as the root. NULL if the node does not exist.
- The simplest way is to traverse directly.
- On this basis, we can also reduce the search according to the nature of binary search tree.
public TreeNode searchBST(TreeNode root, int val) { if(root == null) return null; if(root.val == val) return root; if(root.val > val) return searchBST(root.left); if(root.val < val) return searchBST(root.right); return null; }
701. Insert operation in binary search tree
701. Insert operation in binary search tree
Given the root node of the binary search tree and the value to be inserted into the tree, insert the value into the binary search tree. Returns the root node of the inserted binary search tree. The input data ensures that the new value is different from any node value in the original binary search tree.
- Find the correct location and insert the value into the binary search tree
public TreeNode insertIntoBST(TreeNode root, int val) { if(root == null) return newTreeNode(val); if(root.val > val) root.left = insertIntoBST(root.left, val); if(root.val < val) root.right = insertIntoBST(root.right, val); return root; }
450. Delete the node in the binary search tree
450. Delete the node in the binary search tree
Given the root node root and a value key of a binary search tree, 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 a binary search tree that may be updated.
-
To delete a node, first find the node. Find the node of the given value, that is, the search in the binary search tree, which is very simple.
-
There will be these situations when found.
① This node has no left and right child nodes and can be deleted directly.
② This node has left child node or right child node. After deleting this node, you need to let the left child node or right child node replace the position of the deleted node.
③ This node has a left child node and a right child node. After deletion, you need to judge who will take over your position. [recall the characteristics of binary search tree, right node > root node > left node. After deleting the root node, find the minimum value of the right node (or the maximum value of the left node) as the root node] -
First write the framework according to question 700, and then consider the details.
public TreeNode deleteNode(TreeNode root, int key) { if(root == null) return null; if(root.val == key){ //Three cases //1. No left and right child nodes if(root.left == null && root.right == null) return null; //2. There are left child nodes or right child nodes if(root.left == null) return root.right; if(root.right == null) return root.left; //3. There are left and right child nodes. Find the minimum value of the right subtree as the root node if(root.left != null && root.right != null){ TreeNode minNode = getMin(root.right); root.val = minNode.val; //Delete the node with minNode.val in the right subtree root.right = deleteNode(root.right, minNode.val); } }else if(root.val > key){ root.left = deleteNode(root.left, key); }else if(root.val < key){ root.right = deleteNode(root.right, key); } return root; } //Find minimum public TreeNode getMin(TreeNode node){ //The leftmost leaf node is the smallest while(node.left != null) node = node.left; return node; }
(III)
96. Different binary search trees
96. Different binary search trees
Give you an integer n and find how many kinds of binary search trees are composed of exactly n nodes with different node values from 1 to n? Returns the number of binary search trees that meet the meaning of the question.
- To construct a binary tree, we must first consider the root node. Obviously, each number [1,n] in this question can be used as the root node.
- Traverse each number as the root node.
- If x is taken as the root node, the number of such cases depends on how many different binary trees can be formed by the left and right subtrees. The case where the root node can be composed is equal to left ✖ right
- left = count ( lo, x-1),right = count ( x+1, hi )
[the function count (int lo, int HI) calculates how many different binary trees [lo, hi] can form.] - Therefore, this problem is ergodic and recursive, and there is also an emphasis on the iterator problem.
public int numTrees(int n) { return count(1, n); } public int count(int lo, int hi){ //There is recursion. Remember to write the conditions that jump out of recursion if(lo > hi) return 1; //Traversal [lo - hi] int res = 0; for(int i=lo; i<=hi; i++){ int left = count(lo, i-1); int right = count(i+1, hi); res += left * right; } return res; }
The above solution does not solve the overlapping subproblem, but is solved by exhaustive method.
Use dynamic programming solution to solve the problem from bottom to top.
- According to the title, it is the array length, not the array content, that determines the number of different binary trees.
- Determine dp [] array, dp[0] = 1, dp[1] = 1, dp[2] = 2... And find dp[n]
public int numTrees(int n) { int[] dp = new int[n + 1]; dp[0] = 1; dp[1] = 1; //Calculate dp[i] until dp[n] is found for (int i = 2; i <= n; ++i) { //Traverse the number of different binary trees with the number in this array as the root node, and finally accumulate to get dp[i] //The length is i, let j be the root node, the length of the left array is [j-1], and the length of the right array is [i-j] for (int j = 1; j <= i; ++j) { //dp[i] = sum of these Traversals dp[i] += dp[j - 1] * dp[i - j]; } } return dp[n]; }
95. Different binary search trees II
95. Different binary search trees II
Give you an integer n, please generate and return all different binary search trees composed of N nodes with different node values from 1 to n. You can return answers in any order.
- Enumerate all root nodes
- Recursively construct all left and right subtrees [list < treenode > type]
- Use the loop to make the root node connect all these subtrees
public List<TreeNode> generateTrees(int n) { return build(1,n); } public List<TreeNode> build(int lo, int hi){ List<TreeNode> res = new LinkedList<>(); if(lo > hi){ res.add(null); return res; } // Enumerate all possible root nodes. for(int i=lo; i<=hi; i++){ List<TreeNode> lefts = build(lo, i-1); List<TreeNode> rights = build(i+1, hi); // Recursively construct all legal BST S of left and right subtrees. for(TreeNode left : lefts ){ for(TreeNode right : rights){ //Use these left and right subtrees to construct a binary tree TreeNode root = new TreeNode(i); root.left = left; root.right = right; res.add(root); } } } return res; }
Thank you for seeing here 😛😛, Go and brush more questions. No matter how much you see, you might as well settle down and have a try 😎