代码随想录算法训练营第18天|669. 修剪二叉搜索树、108. 将有序数组转换为二叉搜索树、538. 把二叉搜索树转换为累加树

669. 修剪二叉搜索树

从根节点向下遍历二叉搜索树,找到不是[low,high]范围内的节点就删除节点

class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
		if(root == null){
			return null;
		}
		if(root.val > high) {//[low,high]都在左子树上
			return trimBST(root.left, low, high);
		}else if(root.val < low) {//[low,high]都在右子树上
			return trimBST(root.right, low, high);
		}else {
			root.left = trimBST(root.left, low, high);
			root.right = trimBST(root.right, low, high);
			return root;
		}
    }
}

 ——————————————————————————————————————————

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

 

要转换为一棵 平衡 二叉搜索树,需要根节点的左右子树的最大深度差不超过1
那么就将nums数组平分为两组,分别组成左右子树
后序遍历构建二叉树 

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
		return sortedArrayToBSTFunc(nums, 0, nums.length);
    }
	//左闭右开
	private TreeNode sortedArrayToBSTFunc(int[] nums, int start, int end) {
		if(end - start < 1){
			return null;
		}

		int rootIndex = (start + end) / 2;
		TreeNode root = new TreeNode(nums[rootIndex]);
		root.left = sortedArrayToBSTFunc(nums, start, rootIndex);
		root.right = sortedArrayToBSTFunc(nums, rootIndex + 1, end);
		return root;
	}
}

 ——————————————————————————————————————————

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

 

右中左的遍历顺序
记录上个遍历的节点的值,当前节点的值改为当前节点的值加上上一个节点的值

class Solution {
	TreeNode pre;
    public TreeNode convertBST(TreeNode root) {
		convertBSTFunc(root);
		return root;
    }

	public void convertBSTFunc(TreeNode root) {
		if(root == null){
			return;
		}
		convertBST(root.right);
		if(pre != null){
			root.val += pre.val;
		}
		pre = root;
		convertBST(root.left);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值