和之前的通过后序遍历 中序遍历构造二叉树几乎差不多
通过数组 和 下标begin end 来 划分左子树 和 右子树
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return buildTree(nums, 0, nums.length);
}
private TreeNode buildTree(int[] nums, int begin, int end){
if(begin >= end){
return null;
}
int max = -1;
int index = -1;
for(int i = begin; i < end; i++){
if(nums[i] > max){
max = nums[i];
index = i;
}
}
TreeNode root = new TreeNode(max);
root.left = buildTree(nums, begin, index);
root.right = buildTree(nums, index + 1, end);
return root;
}
}
使用什么顺序遍历都是可以的
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;
}
TreeNode root = new TreeNode(root1.val + root2.val); // 中
root.left = mergeTrees(root1.left, root2.left); // 左
root.right = mergeTrees(root1.right, root2.right); // 右
return root;
}
}
注意是二叉搜索树
可以使用二叉搜索树的特性
递归函数需要有返回值来提前终止递归 因为找到了就可以直接返回了 没必要在搜索下去
普通的二叉树的解法 注意 通过判断left的值来判断是否需要提前返回
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 searchBST(TreeNode root, int val) {
if(root == null || root.val == val){
return root;
}
if(val > root.val){
return searchBST(root.right, val);
}
return searchBST(root.left, val);
}
}
和上一题一样 通过递归的返回值来提前判断
class Solution {
TreeNode max = null;
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;
}
}