669. 修剪二叉搜索树
题目链接:https://leetcode.com/problems/trim-a-binary-search-tree
Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
Output: [3,2,null,1]
思路:
[1, 3]区间在二叉搜索树的中可不是单纯的节点3和左孩子节点0就决定的,还要考虑节点0的右子树。
递归法:
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);
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.将有序数组转换为二叉搜索树
题目链接:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
思路:
- 由于高度平衡,找中间节点分割,递归左区间右区间
- 遵循区间循环不变量,左闭右开(此处采用)
递归法
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums.length == 0) return null;
int mid = nums.length/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(Arrays.copyOfRange(nums, 0, mid));
root.right = sortedArrayToBST(Arrays.copyOfRange(nums, mid+1, nums.length));
return root;
}
}
递归法,有helper function
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return traversal(nums, 0, nums.length);
}
private TreeNode traversal(int[] nums, int left, int right) {
if (left >= right) return null; //注意返回条件,左闭右开,二分法(不只是length=0)
int mid = left + ((right - left) / 2);
TreeNode root = new TreeNode(nums[mid]);
root.left = traversal(nums, left, mid);
root.right = traversal(nums, mid+1, right);
return root;
}
}
538.把二叉搜索树转换为累加树
题目链接:https://leetcode.com/problems/convert-bst-to-greater-tree/
思路:
- 看成有序数组,从后向前累加
- 右中左,反序遍历,再顺序累加
递归法,用全局变量sum累加
class Solution {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
if (root == null) return null;
convertBST(root.right);
sum += root.val;
root.val = sum;
convertBST(root.left);
return root;
}
}
递归法,用全局变量pre,前后指针赋值,helper function递归没有返回值
class Solution {
TreeNode pre = null; //记录前一个节点
public TreeNode convertBST(TreeNode root) {
traversal(root);
return root;
}
private void traversal(TreeNode node) { //不需要返回值操作,遍历整棵树
if (node == null) return;
traversal(node.right);
if (pre != null) node.val += pre.val;
pre = node;
traversal(node.left);
}
}