LeetCode669修剪二叉搜索树

题目链接

https://leetcode-cn.com/problems/trim-a-binary-search-tree/

题解

  • 递归解法
  • 我看了题解写出来的,我分析题目的时候以为还要交换左右子树什么的……,其实不用
  • 思路见代码注释
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Problem: LeetCode 669
// URL: https://leetcode-cn.com/problems/trim-a-binary-search-tree/
// Tags: Tree BST Recursion
// Difficulty: Easy

struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
};

class Solution{
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
// 处理空链表
if (root == nullptr) return nullptr;
// 如果根结点小于L,则根结点以及左子树会被剪掉,整个树的修剪结果是修剪后的右子树
if (root->val < L) return trimBST(root->right, L, R);
// 如果根结点小于L,则根结点以及右子树会被剪掉,整个树的修剪结果是修剪后的左子树
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;
}
};

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!