【LeetCode】669. Trim a Binary Search Tree
程序员文章站
2022-05-28 19:38:28
...
题目:修剪二叉树
题目要求:修剪掉在[L,R]之外的节点。
思路:递归
从根节点出发,若根节点 < L,则保留右子树,抛弃左子树
若根节点 > R ,则保留左子树,抛弃右子树
特殊情况考虑之后,则需要左右子树遍历
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)
return null;
if(root -> val < L)
return trimBST(root -> right, L, R);
else if(root -> val > R)
return trimBST(root -> left, L, R);
else{
root -> left = trimBST(root -> left, L, R);
root -> right = trimBST(root -> right, L, R);
return root;
}
}
};
(我现在还不会怎么输入二叉树来判断代码是否正确,等了解后再补全代码) 上一篇: Numpy教程
推荐阅读
-
leetcode笔记:Invert Binary Tree
-
Convert Sorted Array to Binary Search Tree
-
【leetcode】-700. Search in a Binary Search Tree 查找二叉搜索树
-
LeetCode C++ 454. 4Sum II【Hash Table/Sort/Two Pointers/Binary Search】
-
Leetcode——108. Convert Sorted Array to Binary Search Tree
-
Leetcode 108. Convert Sorted Array to Binary Search Tree
-
LeetCode 236 -- 二叉树的最近公共祖先 ( Lowest Common Ancestor of a Binary Tree ) ( C语言版 )
-
LeetCode 235--二叉搜索树的最近公共祖先 ( Lowest Common Ancestor of a Binary Search Tree ) ( C语言版 )
-
LeetCode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树
-
235. Lowest Common Ancestor of a Binary Search Tree