654. 最大二叉树
本题使用递归类似于二分
重点是思考递归的返回值类型以及在什么地方进行recursion call
public TreeNode constructMaximumBinaryTree(int[] nums) {
if (nums == null) return null;
return rec(nums, 0, nums.length - 1);
}
private TreeNode rec(int[] nums, int lo, int hi){
if (lo > hi) return null;
int max = lo;
for (int i = lo + 1; i <= hi; i++){
if (nums[i] >= nums[max]) max = i;
}
TreeNode curr = new TreeNode(nums[max]);
curr.left = rec(nums, lo, max - 1);
curr.right = rec(nums, max + 1, hi);
return curr;
}
617. 合并二叉树
重点思想在于借用两个二叉树中的一个作为需要返回的二叉树
在此基础上根据另一棵树的结构对这个选定的二叉树进行值的更新及叶子节点拓展
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;
}
700. 二叉搜索树中的搜索
比较简单,思路类似于二分法的递归实现
public TreeNode searchBST(TreeNode root, int val) {
if (root == null) return null;
if (root.val == val) return root;
if (root.val > val) return searchBST(root.left, val);
else return searchBST(root.right, val);
}
98. 验证二叉搜索树
题目需要考虑的情况比较多,尤其是每个subtree和上面节点的大小关系
使用max节点来存储最大/最小值
需复习
TreeNode max;
public boolean isValidBST(TreeNode root) {
if (root == null) return true;
boolean left = isValidBST(root.left);
if (!left) return false;
if (max != null && root.val <= max.val) return false;
max = root;
boolean right = isValidBST(root.right);
return right;
}