class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return constructMaximumBinaryTree1(nums, 0, nums.length);
}
public TreeNode constructMaximumBinaryTree1(int[] nums, int leftIndex, int rightIndex){
if(rightIndex - leftIndex < 1){
return null;
}
if(rightIndex - leftIndex == 1){
return new TreeNode(nums[leftIndex]);
}
int maxIndex = leftIndex;
int maxValue = nums[leftIndex];
for(int i = leftIndex + 1; i < rightIndex; i++){
if(nums[i] > maxValue){
maxValue = nums[i];
maxIndex = i;
}
}
TreeNode root = new TreeNode(maxValue);
root.left = constructMaximumBinaryTree1(nums, leftIndex, maxIndex);
root.right = constructMaximumBinaryTree1(nums, maxIndex+1, rightIndex);
return root;
}
}
class Solution {
// 递归
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null) return root2;
if (root2 == null) return root1;
root1.val += root2.val;
root1.left = mergeTrees(root1.left,root2.left);
root1.right = mergeTrees(root1.right,root2.right);
return root1;
}
}
class Solution {
// 递归,普通二叉树
public TreeNode searchBST(TreeNode root, int val) {
if (root == null || root.val == val) {
return root;
}
TreeNode left = searchBST(root.left, val);
if (left != null) {
return left;
}
return searchBST(root.right, val);
}
}
class Solution {
TreeNode max;
public boolean isValidBST(TreeNode root) {
if(root == null){
return true;
}
boolean left = isValidBST(root.left);
if(!left){
return false;
}
if(max != null && max.val >= root.val) {
return false;
}
max = root;
boolean right = isValidBST(root.right);
if(!right){
return false;
}
return left || right;
}
}