LeeCode Practice Journal | Day_21 Binary Tree08

669. 修建二叉搜索树

题目:669. 修剪二叉搜索树 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
若节点值大于区间,则其右子树均大于区间:
若节点值小于区间,则其左子树均小于区间

solution
public class Solution {
    public TreeNode TrimBST(TreeNode root, int low, int high) {
        if(root == null) return root;

        if(root.val < low) return TrimBST(root.right, low, high);
        else if(root.val > high) return TrimBST(root.left, low, high);
        else
        {
            root.left = TrimBST(root.left, low, high);
            root.right = TrimBST(root.right, low, high);
            return root;
        }
    }
}
summary

错误:

大于/小于区间时直接返回了左/右子树,而没有对子树进行修剪
错误代码:

public class Solution {
    public TreeNode TrimBST(TreeNode root, int low, int high) {
        if(root == null) return root;

        if(root.val < low) return root.right;
        else if(root.val > high) return root.left;
        else
        {
            root.left = TrimBST(root.left, low, high);
            root.right = TrimBST(root.right, low, high);
            return root;
        }
    }
}

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

题目:108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
在怎么取每次的根节点的时候纠结了一会,对平衡二叉树的递归性认识不够

solution
public class Solution {
    public TreeNode SortedArrayToBST(int[] nums) {
        TreeNode root = constructTraversal(nums, 0, nums.Length - 1);
        return root;
    }

    public TreeNode constructTraversal(int[] nums, int start, int end)
    {
        if(start > end) return null;

        int index = start + (end - start) / 2;
        TreeNode root = new TreeNode(nums[index]);
        root.left = constructTraversal(nums, start, index - 1);
        root.right = constructTraversal(nums, index + 1, end);
        return root;
    }
}
summary

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

题目:538. 把二叉搜索树转换为累加树 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
右中左的遍历顺序?

solution
public class Solution {
    public int sum = 0;
    public TreeNode ConvertBST(TreeNode root) {
        if(root == null) return null;

        root.right = ConvertBST(root.right);
        sum += root.val;
        root.val = sum;
        root.left = ConvertBST(root.left);
        return root;
    }
}
summary

key:

因为遍历到一个节点想要知道所有值大于其的节点的值,所以从大向小遍历

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值