98.验证二叉搜索树
class Solution {
public boolean isValidBST(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode pre = null;
if(root != null){
stack.add(root);
}
while(!stack.isEmpty()){
TreeNode curr = stack.peek();
if(curr != null){
stack.pop();
if(curr.right != null){
stack.add(curr.right);
}
stack.add(curr);
stack.add(null);
if(curr.left != null){
stack.add(curr.left);
}
}else {
stack.pop();
TreeNode temp = stack.pop();
if(pre != null && pre.val >= temp.val){
return false;
}
pre = temp;
}
}
return true;
}
}
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 {
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 constructMaximumBinaryTree(int[] nums) {
if(nums.length == 0){
return null;
}
int max = 0;
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0 ; i < nums.length ; i++){
max = Math.max(max,nums[i]);
map.put(nums[i],i);
}
int index = map.get(max);
TreeNode root = new TreeNode(max);
int[] leftNums = new int[index];
int[] rightNums = new int[nums.length-1-index];
for(int i = 0 ; i < index; i ++){
leftNums[i] = nums[i];
}
for(int i = index+1 ; i < nums.length ; i++){
rightNums[i-(index+1)] = nums[i];
}
root.left = constructMaximumBinaryTree(leftNums);
root.right = constructMaximumBinaryTree(rightNums);
return root;
}
}