LeetCode 669. Trim a Binary Search Tree修剪二叉搜索树 (C++)
題目:
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 2L = 1R = 2Output: 1\2?
Example 2:
Input: 3/ \0 4\2/1L = 1R = 3Output: 3/ 2 /1分析:
給定一個(gè)二叉搜索樹(shù),同時(shí)給定最小邊界L?和最大邊界?R。通過(guò)修剪二叉搜索樹(shù),使得所有節(jié)點(diǎn)的值在[L, R]中 (R>=L) 。你可能需要改變樹(shù)的根節(jié)點(diǎn),所以結(jié)果應(yīng)當(dāng)返回修剪好的二叉搜索樹(shù)的新的根節(jié)點(diǎn)。
二叉搜索樹(shù)樹(shù)的性質(zhì)是,左子樹(shù)上所有結(jié)點(diǎn)的值均小于它的根結(jié)點(diǎn)的值,右子樹(shù)上所有結(jié)點(diǎn)的值均大于它的根結(jié)點(diǎn)的值,它的左、右子樹(shù)也分別為二叉搜索樹(shù)。
所以如果當(dāng)前的節(jié)點(diǎn)的值小于L的話,我們就要遞歸執(zhí)行當(dāng)前節(jié)點(diǎn)的右子樹(shù),因?yàn)樽笞訕?shù)上所有節(jié)點(diǎn)的值也均小于當(dāng)前節(jié)點(diǎn)的值,自然也小于L。同理如果當(dāng)前的節(jié)點(diǎn)的值大于R的話,就要遞歸執(zhí)行當(dāng)前節(jié)點(diǎn)的左子樹(shù),因?yàn)樽笞訕?shù)上節(jié)點(diǎn)的值才可能在范圍內(nèi)。這兩種情況當(dāng)前節(jié)點(diǎn)都是需要改變的。之后遞歸執(zhí)行左右子樹(shù)即可。
程序:
/*** 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;} };轉(zhuǎn)載于:https://www.cnblogs.com/silentteller/p/10903474.html
總結(jié)
以上是生活随笔為你收集整理的LeetCode 669. Trim a Binary Search Tree修剪二叉搜索树 (C++)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 关于各组评价的自我评价
- 下一篇: vue组件开发脚手架(vue-sfc-r