leetcode 654.最大二叉树
注意:×
- 使用外面的build函数而不是直接使用原本的
constructMaximumBinaryTree
函数 - 注意lo和hi的使用,在for循环中是[lo,hi]
public TreeNode constructMaximumBinaryTree(int[] nums) {
return build(nums,0,nums.length-1);
}
private TreeNode build(int[] nums, int lo, int hi) {
if (lo>hi){return null;}
int index = -1;
int maxValue = Integer.MIN_VALUE;
for (int i = lo; i <= hi; i++) {
int tmp = nums[i];
if (tmp>maxValue){
index = i;
maxValue = tmp;
}
}
TreeNode root = new TreeNode(maxValue);
root.left = build(nums,lo,index-1);
root.right = build(nums,index+1,hi);
return root;
}
leetcode617. 合并二叉树
注意:√
- 学习了上一题的内容,其实还是好写的
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
return merge(root1, root2);
}
private TreeNode merge(TreeNode root1, TreeNode root2) {
if (root1 == null) {
return root2;
} else if(root2 == null) {
return root1;
}
// 合并操作
int rootVal = root1.val+ root2.val;
TreeNode root = new TreeNode(rootVal);
root.left = merge(root1.left,root2.left);
root.right = merge(root1.right,root2.right);
// 返回值
return root;
}
leetcode700.二叉搜索树中的搜索
注意:√
- 看完书,一遍过
- 注意第一段的写法,需要学习深刻理解递归
public TreeNode searchBST(TreeNode root, int val) {
if (root == null){return null;}
if (root.val>val){
return searchBST(root.left, val);
}else if (root.val<val){
return searchBST(root.right, val);
}
return root;
}
public TreeNode searchBST(TreeNode root, int val) {
if (root == null){return null;}
TreeNode node = null;
if (root.val>val){
node = searchBST(root.left, val);
}else if (root.val<val){
node = searchBST(root.right, val);
}else if(root.val == val){
return root;
}
return node;
}
leetcode98.验证二叉搜索树
注意:×
- 看书后抄的,记得回头看
public boolean isValidBST(TreeNode root) {
return isValid(root,null,null);
}
private boolean isValid(TreeNode root, TreeNode min, TreeNode max) {
if (root == null){return true;}
if (min!=null && root.val <= min.val){return false;}
if (max!=null && root.val >= max.val){return false;}
return isValid(root.left,min,root) && isValid(root.right, root, max);
}