669. Trim a Binary Search Tree

题目:

Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

 

Example 1:

669. Trim a Binary Search Tree

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

Example 2:

669. Trim a Binary Search Tree

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

Example 3:

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

Example 4:

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

Example 5:

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

 

Constraints:

  • The number of nodes in the tree in the range [1, 10^4].
  • 0 <= Node.val <= 10^4
  • The value of each node in the tree is unique.
  • root is guaranteed to be a valid binary search tree.
  • 0 <= low <= high <= 10^4

 

 

 

思路:

有两种方法,一种比较繁琐的是先读一遍整棵树,找到在[low, high]中的对应点并记录下来,可以用哈希表也可以用vector,然后再重建一个树即可。这里介绍思路更简单的递归,首先如果当前node为空直接返回,之后因为我们最后要返回root,所以最后处理左和右,再返回本身的root。接下来分类讨论:两种情况。如果当前值在low和high之外:如果当前值小于low,那么root的左子肯定更小,不符合,我们只要递归root的右子即可;如果当前值大于high,相应的,我们只要递归root的左子即可。如果当前值在low和high之内,直接处理左右子即可。最后返回root本身。

 

 

 

 

 

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        if (!root) return NULL;
        if (root->val < low)
            return trimBST(root->right, low, high);
        if (root->val > high)
            return trimBST(root->left, low, high);
        root->left = trimBST(root->left, low, high);
        root->right = trimBST(root->right, low, high);
        return root;
    }
};

上一篇:登录界面与代码


下一篇:v-model.trim用法及其他修饰符