递归
LeetCode递归题目
合并两个有序链表:easy
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
if (l1->val <= l2->val){
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}else{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return ismirror(root, root);
}
bool ismirror(TreeNode* t1, TreeNode* t2){
if (t1== NULL && t2==NULL) return true;
if (t1==NULL || t2== NULL) return false;
return (t1->val == t2-> val) && (ismirror(t1->left, t2->right)) &&ismirror(t1->right, t2->left);
}
};
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return max(left, right)+1;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q){
//先找到p或者q就返回
if(root == NULL || root == p || root == q)
return root;
//在左右子树中找p和q
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left == NULL) return right; //left为空,说明不在左子树
if(right == NULL) return left; //right为空,说明不在左子树
return root; //left、right均不为空,说明p、q在root左右两边
}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return root;
TreeNode* tmp = root->left;
root->left = root->right;
root->right = tmp;
invertTree(root->left);
invertTree(root->right);
return root;
}
};