classSolution { public TreeNode trimBST(TreeNode root, int low, int high) { if (root == null) { returnnull; } // as this is a BST, if root's val is larger than high // then all the right side nodes should be removed if (root.val > high) { return trimBST(root.left, low, high); } // the same with the left side if (root.val < low) { return trimBST(root.right, low, high); } // else, it means that root is within the target range // thus trim its child nodes root.left = trimBST(root.left, low, high); root.right = trimBST(root.right, low, high); return root;
classSolution { public TreeNode sortedArrayToBST(int[] nums) { // as I do not wanna change the array itself thus I choose to use to helper // function and express the range return buildBST(nums, 0, nums.length); }
// build the tree and return the root node in range [startIndex, endIndex) private TreeNode buildBST(int[] nums, int startIndex, int endIndex){ if (startIndex >= endIndex) { returnnull; }
privatevoidmyConvertTree(TreeNode root) { if (root == null) { return; }
// reflect the target tree, we can find that it starts counting // with the right node, then root node // and then the left node, thus we can traverse the tree in a variant in-order // i.e. right mid left myConvertTree(root.right);
// use a temp variable to record the updated value of the prev node thus we can // change all the nodes in one traverse if (temp != Integer.MIN_VALUE) { root.val += temp; }