《剑指offer》相关题目
《剑指offer》系列 二叉搜索树的后序遍历序列(Java)
class Solution {
public boolean isValidBST(TreeNode root) {
return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean helper(TreeNode root, long lower, long high){
if(root == null){
return true;
}
if(root.val <= lower || root.val >= high){
return false;
}
return helper(root.left, lower, root.val) && helper(root.right, root.val, high);
}
}
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return help(nums, 0, nums.length - 1);
}
public TreeNode help(int[] nums, int first, int last) {
if (first > last) {
return null;
}
int mid = (first + last) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = help(nums, first, mid - 1);
node.right = help(nums, mid + 1, last);
return node;
}
}
538. 把二叉搜索树转换为累加树
1038. 把二叉搜索树转换为累加树
class Solution {
public TreeNode convertBST(TreeNode root) {
reverse(root);
return root;
}
int max = 0;
public void reverse(TreeNode root) {
if(root==null){
return;
}
reverse(root.right);
root.val += max;
max = root.val;
reverse(root.left);
}
}