LeetCode 669. Trim a Binary Search Tree

来源:互联网 发布:java培训视频教程 编辑:程序博客网 时间:2024/05/17 01:17

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

递归的思想还要继续深入啊~

/** * 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;    }};/* * 当root的值位于L和R之间,则递归修剪其左右子树,返回root。 * 当root的值小于L,则其左子树的值都小于L,抛弃左子树,返回修剪过的右子树。 * 当root的值大于R,则其右子树的值都大于R,抛弃右子树,返回修剪过的左子树。 */
原创粉丝点击