LeetCode 669. Trim a Binary Search Tree (Easy)

来源:互联网 发布:bbs.h5dm新域名 编辑:程序博客网 时间:2024/05/17 02:29

题目描述:

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.

Example1:

Input:     1   / \  0   2  L = 1  R = 2Output:     1      \       2

Example2:

Input:     3   / \  0   4   \    2   /  1  L = 1  R = 3Output:       3     /    2     / 1

题目大意:给一个二叉搜索树,一个闭区间,把搜索树中小于或者大于区间的节点去掉,返回新树的根。

思路:递归,如果左节点值小于区间左侧,那么剪掉左侧,如果右节点值大于区间右侧,剪掉右侧。

c++代码:

/** * 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 nullptr;        if (root->val < L)            return trimBST(root->right, L, R);        if (root->val > R)            return root = trimBST(root->left, L, R);        else        {            root->left = trimBST(root->left, L, R);            root->right = trimBST(root->right, L, R);            return root;        }    }};
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 宠物市场网 宠物买卖网 卖小狗的网站 宠物交易平台 狗狗交易 小狗电器 狗狗论坛 狗狗网站 宠物交易市场 吉娃娃幼犬出售 萨摩耶市场价 狗崽 狗狗宠物 养狗指南 购买狗狗 网上哪里可以买狗 哪里有卖宠物狗 什么网站可以买狗 那个网站可以买狗 哪个网站卖宠物狗 价格便宜的宠物狗 猪里脊肉去买肉怎么叫 欲钱买猪先生打一生肖 买宠物猪 脆皮烤猪为什么没人买 买猫猫 快买猫记录生活记录你gif 买猫去哪个网站 快买猫记录生活记你 买猫注意事项 买猫 买猫去哪里买 快猫记录生活记你 哪里买宠物猫 买猫网 宠物猫购买 在哪里买猫 网上买猫 怎么买猫 宠物猫在哪里买 买宠物猫