递归函数的解题步骤
-
- 确定递归函数的参数和返回值
-
- 确定终止条件
-
- 确定单层递归的逻辑
654. 最大二叉树
654. 最大二叉树
本题类似于106. 从中序与后序遍历序列构造二叉树
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
//用下标来切割数组
return constructMaximumBinaryTree1(nums,0,nums.length);
}
public TreeNode constructMaximumBinaryTree1(int[] nums,int leftIndex , int rightIndex){
//左闭右开
if(rightIndex - leftIndex < 1){
//说明数组中没有元素了
return null;
}
if(rightIndex - leftIndex == 1){
//只有一个元素
return new TreeNode(nums[leftIndex]);
}
int maxIndex = leftIndex;//最大值所在的位置
int maxVal = nums[maxIndex];//最大值
for(int i = leftIndex + 1; i< rightIndex ; i++){ //找到数组中的最大元素
if(nums[i] > maxVal){
maxVal = nums[i];
maxIndex = i;
}
}
TreeNode root = new TreeNode(maxVal);
root.left = constructMaximumBinaryTree1(nums,leftIndex,maxIndex);
root.right = constructMaximumBinaryTree1(nums,maxIndex+1 ,rightIndex);
return root;
}
}
617. 合并二叉树
- 递归法
class Solution {
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;
}
}
- 迭代法
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if (t1 == NULL) return t2;
if (t2 == NULL) return t1;
queue<TreeNode*> que;
que.push(t1);
que.push(t2);
while(!que.empty()) {
TreeNode* node1 = que.front(); que.pop();
TreeNode* node2 = que.front(); que.pop();
// 此时两个节点一定不为空,val相加
node1->val += node2->val;
// 如果两棵树左节点都不为空,加入队列
if (node1->left != NULL && node2->left != NULL) {
que.push(node1->left);
que.push(node2->left);
}
// 如果两棵树右节点都不为空,加入队列
if (node1->right != NULL && node2->right != NULL) {
que.push(node1->right);
que.push(node2->right);
}
// 当t1的左节点 为空 t2左节点不为空,就赋值过去
if (node1->left == NULL && node2->left != NULL) {
node1->left = node2->left;
}
// 当t1的右节点 为空 t2右节点不为空,就赋值过去
if (node1->right == NULL && node2->right != NULL) {
node1->right = node2->right;
}
}
return t1;
}
};
700. 二叉搜索树中的搜索
- 注意二叉搜索树的性质,父节点val和子树节点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.left,val);
}
else {
return searchBST(root.right,val);
}
}
}
98. 验证二叉搜索树
比较直观的方式解题,本题不用转变成数组来判断是否有序,而是在递归遍历的过程中判断是否有序。
class Solution {
TreeNode max;
public boolean isValidBST(TreeNode root) {
//二叉搜索树的中序遍历结果是有序的
if(root == null){
return true;
}
boolean left = isValidBST(root.left);
if(max != null && root.val <= max.val){
return false;
}
//取最左边节点的值来比较
max = root;
boolean right = isValidBST(root.right);
return right && left;
}
}