700. 二叉搜索树中的搜索
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if(root.val==val||root==null) return root; //1:终止条件
if(root.val>val) return searchBST(root.left,val); //2:不是左便是右 (前提是一定在其中)
else return searchBST(root.right,val);
}
}
617. 合并二叉树
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
return merge(root1,root2);
}
public TreeNode merge(TreeNode root1,TreeNode root2){
if(root1==null&&root2==null) return null; //退出条件
if(root1==null) return root2;
if(root2==null) return root1;
root1.val=root1.val+root2.val; //中 左右
root1.left=merge(root1.left,root2.left);
root1.right=merge(root1.right,root2.right);
return root1;
}
}
98验证二叉搜索树
class Solution {
long max=0;
public boolean isValidBST(TreeNode root) {
max=Long.MIN_VALUE; //测试用例会用 Integer.MIN_VALUE 边界值会出问题
return isTree(root);
}
public boolean isTree(TreeNode root){
if(root==null) return true;
boolean left=isTree(root.left); //利用二叉搜索树的特性 左中右 由小到大
if(max<root.val) max=root.val;
else return false;
boolean right=isTree(root.right);
return left&&right;
}
}
645最大二叉树
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return construtree(nums,0,nums.length);
}
public TreeNode construtree(int[] nums,int leftindex,int rightindex){
if(rightindex-leftindex<1){
return null; //类似二分法 注意边界判断 1
}
if(rightindex-leftindex==1){
return new TreeNode(nums[leftindex]);
}
int maxIndex=leftindex; //2
int maxValue=nums[maxIndex];
for(int i=leftindex;i<rightindex;i++){ 找到范围内最大的下标
if(nums[i]>maxValue){
maxValue=nums[i];
maxIndex=i;
}
}
TreeNode root=new TreeNode(maxValue);
root.left=construtree(nums,leftindex,maxIndex); //3
root.right=construtree(nums,maxIndex+1,rightindex);
return root;
}
标签:TreeNode,val,root,700,98,645,return,root1,root2
From: https://www.cnblogs.com/wdnmdp/p/16777470.html