二叉搜索树的应用
669.修剪二叉树
对二叉树进行更改的情况, 都需要递归的构造二叉树的左右子节点 递归法:
- 若当前节点值合法, 则继续递归
- 若当前值比最大的值大, 则需要往左继续寻找, 此时将找到的合法左子节点返回上去即可
- 若当前的值比最小的小, 则需要往右继续寻找, 此时将找到的合法右子节点返回上去即可
代码:
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if(root == null) return null;
// 需要修剪
if(root.val > high) {
return trimBST(root.left, low, high);
}else if(root.val < low){
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.如果每次选中位数进行构造, 最终就会形成一个平衡二叉搜索树
代码:
class Solution {
// 每次选择 中位数 构造根节点, 然后递归的构造左右子节点
// 得到的二叉树一定是平衡二叉搜索树
public TreeNode sortedArrayToBST(int[] nums) {
return dfs(nums, 0, nums.length);
}
public TreeNode dfs(int[] nums, int start, int end) {
if(start >= end) return null;
int index = (start + end) >> 1;
TreeNode root = new TreeNode(nums[index]);
root.left = dfs(nums, start, index);
root.right = dfs(nums, index + 1, end);
return root;
}
}
538.把二叉搜索树转化为累加树
- 对二叉树进行右-根-左的递归方式
- 同时用sum变量不断累加路径和, 当前root的值就为sum的和
代码:
class Solution {
// 遍历方式为右-左-根: 然后对遍历过的路径进行累加和
int sum = 0;
public TreeNode convertBST(TreeNode root) {
dfs(root);
return root;
}
public void dfs(TreeNode root) {
if(root == null) return;
dfs(root.right);
// 修改根节点的值
sum += root.val;
root.val = sum;
dfs(root.left);
}
}