class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if (nums.length == 1) {
return new TreeNode(nums[0]);
}
int maxVal = 0;
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > maxVal) {
maxVal = nums[i];
index = i;
}
}
TreeNode treeNode = new TreeNode(maxVal);
if (index > 0) {
int[] ints = Arrays.copyOfRange(nums, 0, index);
treeNode.left = constructMaximumBinaryTree(ints);
}
if (index < nums.length - 1) {
int[] ints = Arrays.copyOfRange(nums, index + 1, nums.length);
treeNode.right = constructMaximumBinaryTree(ints);
}
return treeNode;
}
}
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) {
return null;
}
if (root1 != null && root2 == null) {
return root1;
}
if (root1 == null && root2 != null) {
return root2;
}
root1.val = 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) {
return null;
}
if (root.val > val) {
return searchBST(root.left, val);
}
if (root.val < val) {
return searchBST(root.right, val);
}
return root;
}
}
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
while (root != null) {
if (root.val < val) {
root = root.right;
} else if (root.val > val) {
root = root.left;
} else {
return root;
}
}
return null;
}
}
class Solution {
private TreeNode pre;
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
boolean leftResult = isValidBST(root.left);
if (!leftResult) {
return false;
}
if (pre != null) {
if (root.val <= pre.val) {
return false;
}
}
pre = root;
boolean rightResult = isValidBST(root.right);
if (!rightResult) {
return false;
}
return true;
}
}