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,抛弃右子树,返回修剪过的左子树。 */
阅读全文
0 0
- leetcode 669. Trim a Binary Search Tree
- leetcode 669. Trim a Binary Search Tree
- leetcode 669. Trim a Binary Search Tree
- LeetCode 669. Trim a Binary Search Tree
- leetcode 669. Trim a Binary Search Tree
- leetcode: 669. Trim a Binary Search Tree
- <LeetCode>669. Trim a Binary Search Tree
- leetcode 669. Trim a Binary Search Tree
- LeetCode 669. Trim a Binary Search Tree
- [LeetCode] 669.Trim a Binary Search Tree
- [LeetCode] 669.Trim a Binary Search Tree
- 【LeetCode】669 Trim a Binary Search Tree
- Trim a Binary Search Tree(leetcode)
- leetcode- Add to List 669. Trim a Binary Search Tree
- 【LeetCode】669.Trim a Binary Search Tree解题报告
- LeetCode 669. Trim a Binary Search Tree (Easy)
- 669. Trim a Binary Search Tree
- 669. Trim a Binary Search Tree
- 洛谷 P1091 合唱队形
- python中a+=a和a=a+a的区别
- Http的Get/Post请求带有特殊字符,400 Bad Request解决方案
- 5.3
- “足球论之java集合 list set map的区别”
- LeetCode 669. Trim a Binary Search Tree
- JFrame 的层次结构 及 背景设置说明
- 解决Android Studio build grale一直卡着不动问题
- 商城购物车逻辑思路
- 下联网关国标对接中的通信过程分析和实例之客户端主动发起的历史媒体回放过程
- 数据库和专业术语小结
- MVP+Rectrofit+RXJAVA+Fresco
- Android中网络框架Retrofit2.0简单使用
- UpdataPanel控件的使用及注意事项