669:修剪二叉搜索树
题目描述:给你二叉搜索树的根节点 root
,同时给定最小边界low
和最大边界 high
。通过修剪二叉搜索树,使得所有节点的值在[low, high]
中。修剪树 不应该 改变保留在树中的元素的相对结构 (即,如果没有被移除,原有的父代子代关系都应当保留)。 可以证明,存在 唯一的答案 。
因为二叉搜索树的性质,如果当前遍历节点的val小于low,那么当前节点的左子树全部不满足,都应该删除,但右子树不一定,所以需要继续对右子树进行修剪。同理,如果当前遍历节点的val大于high,那么当前节点的右子树全部不满足,都应该删除,但左子树不一定,所以需要继续对右子树进行修剪。如果当前节点的值在low和high之间的话,则分别对左右子树进行遍历。
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root==null) {
return null;
}
if (root.val<low) {
return trimBST(root.right, low, high);
}else if (root.val>high) {
return trimBST(root.left, low, high);
}
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}
108:将有序数组转换为二叉搜索树
题目描述:给你一个整数数组 nums
,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。
思路:要构造高度平衡二叉树,那么讲数组分为两半,取数组中间下标的值作为当前节点,然后左半数组构造左子树,右半数组构造右子树。
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums==null) {
return null;
}
return build(nums, 0, nums.length-1);
}
public TreeNode build(int[] nums, int begin, int end){
if (begin>end) {
return null;
}
int center = (begin + end)/2;
TreeNode node = new TreeNode(nums[center]);
node.left = build(nums, begin, center-1);
node.right = build(nums, center+1, end);
return node;
}
}
538:把二叉搜索树转换为累加树
题目描述:给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node
的新值等于原树中大于或等于 node.val
的值之和。
思路:相当于按照“右中左”的顺序遍历节点,并且每次遍历的节点的值等于前面遍历所有节点的和。
class Solution {
TreeNode pre;
public TreeNode convertBST(TreeNode root) {
if(root==null) return root;
pre = null;
search(root);
return root;
}
public void search(TreeNode root){
if (root == null) {
return;
}
search(root.right);
//处理中间节点
if (pre!=null) {
root.val += pre.val;
}
pre = root;
search(root.left);
}
}
因为不涉及二叉树的结构变化,也可以直接用一个int变量记录前面的累加和。
class Solution {
int sum;
public TreeNode convertBST(TreeNode root) {
sum = 0;
search(root);
return root;
}
public void search(TreeNode root){
if (root == null) {
return;
}
search(root.right);
//处理中间节点
sum += root.val;
root.val = sum;
search(root.left);
}
}