LeetCode 669. Trim a Binary Search Tree修剪二叉搜索树 (C++)

题目:

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.

Example 1:

Input: 
    1
   / \
  0   2

  L = 1
  R = 2

Output: 
    1
      \
       2

Example 2:

Input: 
    3
   / \
  0   4
   \
    2
   /
  1

  L = 1
  R = 3

Output: 
      3
     / 
   2   
  /
 1

分析:

给定一个二叉搜索树,同时给定最小边界L 和最大边界 R。通过修剪二叉搜索树,使得所有节点的值在[L, R]中 (R>=L) 。你可能需要改变树的根节点,所以结果应当返回修剪好的二叉搜索树的新的根节点。

二叉搜索树树的性质是,左子树上所有结点的值均小于它的根结点的值,右子树上所有结点的值均大于它的根结点的值,它的左、右子树也分别为二叉搜索树。

所以如果当前的节点的值小于L的话,我们就要递归执行当前节点的右子树,因为左子树上所有节点的值也均小于当前节点的值,自然也小于L。同理如果当前的节点的值大于R的话,就要递归执行当前节点的左子树,因为左子树上节点的值才可能在范围内。这两种情况当前节点都是需要改变的。之后递归执行左右子树即可。

程序:

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

猜你喜欢

转载自www.cnblogs.com/silentteller/p/10903474.html