当前位置:   article > 正文

代码随想录算法训练营第22天-leetcode-二叉树08:669. 修剪二叉搜索树;108.将有序数组转换为二叉搜索树;538.把二叉搜索树转换为累加树

代码随想录算法训练营第22天-leetcode-二叉树08:669. 修剪二叉搜索树;108.将有序数组转换为二叉搜索树;538.把二叉搜索树转换为累加树

669. 修剪二叉搜索树

力扣题目链接(opens new window)

给定一个二叉搜索树,同时给定最小边界L 和最大边界 R。通过修剪二叉搜索树,使得所有节点的值在[L, R]中 (R>=L) 。你可能需要改变树的根节点,所以结果应当返回修剪好的二叉搜索树的新的根节点。

分析:

需要遍历整棵树,因为父节点被删除或者保留,子节点都有可能删除或者保留;父节点被删除时,左子树和右子树只可能保留一个

我的做法:

后序遍历每个节点,对于在范围外的节点,考虑保留其左子树/右子树(只可能保留一个)

  1. struct TreeNode* trimBST(struct TreeNode* root, int low, int high) {
  2. if(root==NULL) return NULL;
  3. int x=root->val;
  4. root->left=trimBST(root->left, low, high);
  5. root->right=trimBST(root->right, low, high);
  6. if(x<low){
  7. struct TreeNode* b=root->right;
  8. free(root);
  9. return b;
  10. }
  11. else if(x>high){
  12. struct TreeNode* b=root->left;
  13. free(root);
  14. return b;
  15. }
  16. return root;
  17. }

代码随想录:

全部写成递归

  1. struct TreeNode* trimBST(struct TreeNode* root, int low, int high) {
  2. if(root==NULL) return NULL;
  3. int x=root->val;
  4. if(x<low){
  5. return trimBST(root->right, low, high);
  6. }
  7. else if(x>high){
  8. return trimBST(root->left, low, high);
  9. }
  10. root->left=trimBST(root->left, low, high);
  11. root->right=trimBST(root->right, low, high);
  12. return root;
  13. }

 

108.将有序数组转换为二叉搜索树

力扣题目链接(opens new window)

将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

分析:

不断选取中点!

  1. struct TreeNode* buildtree(int* nums,int l,int r){
  2. if (l>r) return NULL;
  3. int mid=(l+r)/2;
  4. struct TreeNode* root=(struct TreeNode* )malloc(sizeof(struct TreeNode));
  5. root->val= nums[mid];
  6. root->left=buildtree(nums, l, mid-1);
  7. root->right=buildtree(nums, mid+1, r);
  8. return root;
  9. }
  10. struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
  11. return buildtree(nums,0,numsSize-1);
  12. }

538.把二叉搜索树转换为累加树

力扣题目链接(opens new window)

给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

提醒一下,二叉搜索树满足下列约束条件:

节点的左子树仅包含键 小于 节点键的节点。 节点的右子树仅包含键 大于 节点键的节点。 左右子树也必须是二叉搜索树。

分析:

二叉搜索树——中序排序

题目要求,实际上是每个节点加上中序排列后面的那个节点,故而可以反向中序排序,即RNL,用prior记录前一个节点的值,加上前一个节点的值即可

  1. void build(struct TreeNode*root,int* prior){
  2. if(root==NULL) return ;
  3. build(root->right,prior);
  4. root->val=root->val+*prior;
  5. *prior=root->val;
  6. build(root->left,prior);
  7. }
  8. struct TreeNode* convertBST(struct TreeNode* root) {
  9. int prior=0;
  10. build(root,&prior);
  11. return root;
  12. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/896506
推荐阅读
相关标签
  

闽ICP备14008679号