public class TrimaBinarySearchTree { 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在[low,high]范围内 root.left = trimBST(root.left, low, high); root.right = trimBST(root.right, low, high); return root; } }
Given an integer array nums
where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
public class ConvertSortedArraytoBinarySearchTree { public TreeNode sortedArrayToBST(int[] nums) { TreeNode root = traversal(nums, 0, nums.length - 1); return root; } // 左闭右闭区间[left, right) private TreeNode traversal(int[] nums, int left, int right){ if(left > right) return null; int mid = (right + left) /2; //数组里下标相加不会爆内存,所以可以这样用 TreeNode root = new TreeNode(nums[mid]); root.left = traversal(nums, left, mid - 1); root.right = traversal(nums, mid + 1, right); return root; } }
public class ConvertBSTtoGreatertTree { //递归 //二叉搜素数是左中右,从小到大,那么从大到小就是右中左 int pre; public TreeNode convertBST(TreeNode root){ pre = 0; convertBST1(root); return root; } // 按右中左顺序遍历,累加即可 public void convertBST1(TreeNode root){ if(root == null) return; //左 convertBST1(root.right); //中 root.val += pre; pre = root.val; //右 convertBST1(root.left); } }