赞
踩
class Solution { public: TreeNode* trimBST(TreeNode* root, int low, int high) { if(root == nullptr){ return root; } if(root->val < low){ return trimBST(root->right, low, high); } if(root->val > high){ return trimBST(root->left, low, high); } root->left = trimBST(root->left, low, high); root->right = trimBST(root->right, low, high); return root; } };
class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { function<TreeNode *(int , int)> dfs = [&](int low, int high) -> TreeNode *{ if(low > high){ return nullptr; } int mid = low + (high - low) / 2; TreeNode *left = dfs(low, mid - 1); TreeNode *right = dfs(mid + 1, high); return new TreeNode(nums[mid], left, right); }; return dfs(0, nums.size() - 1); } };
class Solution { public: TreeNode* convertBST(TreeNode* root) { int sum = 0; function<void(TreeNode *)> dfs = [&](auto node)->void{ if(node == nullptr){ return; } dfs(node->right); sum += node->val; node->val = sum; dfs(node->left); }; dfs(root); return root; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。