/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return constructMaximumBinaryTree1(nums, 0, nums.length);
}
public TreeNode constructMaximumBinaryTree1(int nums[], int startIndex, int endIndex) {
if (startIndex >= endIndex) {
return null;
}
int maxValue = Integer.MIN_VALUE;
int index = 0;
for (int i = startIndex; i < endIndex; i++) {
if (nums[i] > maxValue) {
maxValue = nums[i];
index = i;
}
}
TreeNode root = new TreeNode(maxValue);
root.left = constructMaximumBinaryTree1(nums, startIndex, index);
root.right = constructMaximumBinaryTree1(nums, index + 1, endIndex);
return root;
}
}
思路:
递归函数 constructMaximumBinaryTree1
:
- 如果
startIndex
大于等于endIndex
,返回null。这表示我们已经处理完了子数组或子数组为空。 - 初始化一个
maxValue
为Integer.MIN_VALUE
,以便找到子数组的最大值。 - 遍历当前的子数组(从
startIndex
到endIndex-1
),找到最大值及其索引。 - 使用找到的最大值创建一个新的
TreeNode
作为根。 - 对于左子树,递归地处理从
startIndex
到最大值索引的子数组。 - 对于右子树,递归地处理从最大值索引+1到
endIndex
的子数组。 - 返回当前的根节点。
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1 == null) return root2;
if(root2 == null) return root1;
root1.val = root1.val + root2.val;
root1.left = mergeTrees(root1.left, root2.left);
root1.right = mergeTrees(root1.right, root2.right);
return root1;
}
}
思路:
- 如果
root1
为空,直接返回root2
。因为没有与root2
对应的节点需要相加。 - 如果
root2
为空,直接返回root1
。与上面的原因类似。 - 如果两个根都不为空,将它们的值相加,并将结果存储在
root1.val
。 - 递归地合并
root1
和root2
的左子树,然后合并它们的右子树。 - 返回合并后的
root1
。注意这里返回的其实是已经被修改过的root1
,而不是一个全新的树。
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if(root == null || root.val == val){
return root;
}
if(root.val > val){
return searchBST(root.left, val);
}else{
return searchBST(root.right, val);
}
}
}
思路:
- 首先检查根节点
root
。如果root
为空或root.val
等于目标值val
,则直接返回root
。这是递归的基本情况。 - 如果
root.val
大于目标值val
,那么继续在左子树中搜索val
,因为在二叉搜索树中,所有左子树的值都小于根节点。 - 否则(
root.val
小于目标值val
),在右子树中搜索val
,因为在二叉搜索树中,所有右子树的值都大于根节点
class Solution {
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);
if(!right) return false;
return true;
}
}
思路:
-
TreeNode max;
: 这里定义了一个全局变量max
,用于存储上一个遍历到的节点。在中序遍历过程中,上一个节点的值应该小于当前节点的值,否则不满足BST的条件。 -
在
isValidBST
函数中:- 如果
root
为空,则返回true
,因为空树是BST。 - 递归检查左子树:
boolean left = isValidBST(root.left);
。如果左子树不是BST,则返回false
。 - 检查当前节点的值是否大于
max
(即上一个遍历到的节点的值)。如果不是,则返回false
。 - 更新
max
为当前节点:max = root
- 递归检查右子树:
boolean right = isValidBST(root.right);
。如果右子树不是BST,则返回false
。 - 如果左、右子树都是BST,并且当前节点的值大于上一个节点的值,那么返回
true
,表示到目前为止,所有节点都满足BST的条件。
- 如果