669.修剪二叉搜索树
思路:递归当前子树的左右子树去修剪。当前节点也需要处理
代码框架:
遍历到节点为空就返回。
当前节点如果小于左边界,则当前结点的左子树一定小于左边界,不再考虑。当前节点的右子树需要再修剪,修剪后的结果进行返回,代替当前节点的位置。
大于右边界同理。
递归遍历左右子树。
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if(root == null) return null;
//此处是已经知道当前节点不合法,看当前节点的右子树下还有没有不合法的节点
if(root.val < low){
TreeNode left;
left = trimBST(root.right, low, high);
return left;
}
//此处是已经知道当前节点不合法,看当前节点的左子树下还有没有不合法的节点
if(root.val > high){
TreeNode right;
right = trimBST(root.left, low, high);
return right;
}
root.left = trimBST(root.left, low, high);
root.right = (trimBST(root.right, low, high));
return root;
}
}
108.将有序数组转换为二叉搜索树
思路:因为要转换成平衡二叉树,所以要先找到中间节点,再递归左右子树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return traveral(nums,0, nums.length - 1);
}
public TreeNode traveral(int[]nums, int left, int right){
if(left>right){
return null;
}
int mid = (right + left)>>1;
TreeNode root = new TreeNode(nums[mid]);
root.left = traveral(nums, left, mid-1);
root.right = traveral(nums, mid + 1,right);
return root;
}
}
538.把二叉搜索树转换为累加树
思路:右中左遍历,好像一个指针就够了
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int pre = 0;
int cur;
public TreeNode convertBST(TreeNode root) {
if(root == null){
return null;
}
convertBST(root.right);
root.val += pre;
pre = root.val;
convertBST(root.left);
return root;
}
}