Leetcode leetcode 669. Pruning a binary search tree

insert image description here

Topic link and description

https://leetcode.cn/problems/trim-a-binary-search-tree/

Given the root node root of your binary search tree, you are also given a minimum bound low and a maximum bound high. By pruning the binary search tree, the values ​​of all nodes are in [low, high]. Pruning the tree should not change the relative structure of the elements that remain in the tree (ie, the original parent-child relationship should be preserved if not removed). It can be shown that there is a unique answer.

So the result should return the new root node of the pruned binary search tree. Note that the root node may change according to the given bounds.

Example 1:

Input: root = [1,0,2], low = 1, high = 2
Output: [1,null,2]
Example 2:

Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
Output: [3,2,null,1]

hint:

The number of nodes in the tree is in the range [1, 104]
0 <= Node.val <= 104
The value of each node in the tree is unique
The title data guarantees that the input is a valid binary search tree
0 <= low < = high <= 104

Keywords: binary search tree DFS BFS

Binary Search Tree (Binary Search Tree), (also: Binary Search Tree, Binary Sorting Tree)

It is either an empty tree or a binary tree with the following properties:

  • If its left subtree is not empty, the values ​​of all nodes on the left subtree are less than the value of its root node;
  • If its right subtree is not empty, the values ​​of all nodes on the right subtree are greater than the value of its root node;
  • Its left and right subtrees are also binary sorted trees.

Method 1: DFS recursion

run screenshot

insert image description here

the code

The recursive change to the loop has the same effect


public TreeNode trimBST(TreeNode root, int low, int high) {
    
    
		// 如果传入是空,则返回空即可
		if (root == null) {
    
    
			return root;
		}
		// 如果大于高值,那么可以得到,右侧只会更高。所以只能左子节点递归
		if (root.val > high) {
    
    
			return trimBST(root.left, low, high);
		} else if (root.val < low) {
    
    
		// 如果小于小值,那么左侧只会更低,同理给右子节点
			return trimBST(root.right, low, high);
		}
		// 其他情况等于或者符合要求,正常左+右迭代 给对应的左值右值即可
		root.left = trimBST(root.left, low, high);
		root.right = trimBST(root.right, low, high);
		// 最后返回当前节点
		return root;
	}

end

Welcome to communicate in the comment area, check in every day, and rush! ! !

Guess you like

Origin blog.csdn.net/qq_35530042/article/details/126800344