hot-100-1
简单题第三题:21.合并两个有序链表(方法二:递归)。
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == nullptr) {
return l2;
} else if (l2 == nullptr) {
return l1;
} else if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
如下:2023/4/13自己思考半小时得出流程结果,哎,泪啊!
第六题 94. 二叉树的中序遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>v;
inorder(root,v);
return v;
}
void inorder(TreeNode* root,vector<int> &v)
{
if(!root)return ;
inorder(root->left,v);
v.push_back(root->val);
inorder(root->right,v);
}
};
第七题 递归 二叉树的对称性
class Solution {
public:
bool check(TreeNode *p, TreeNode *q) {
if (!p && !q) return true;
if (!p || !q) return false;
return p->val == q->val && check(p->left, q->right) && check(p->right, q->left);
}
bool isSymmetric(TreeNode* root) {
return check(root, root);
}
};
第八题 二叉树的最大深度
方法一 深度优先 递归:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root)return 0;
int a=maxDepth(root->left);
int b=maxDepth(root->right);
return (a>b)?a+1:b+1;
}
};
234. 回文链表 第16题 23/4/20
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
方法一:官方代码 迭代,太优雅了
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> vals;
while (head != nullptr) {
vals.emplace_back(head->val);
head = head->next;
}
for (int i = 0, j = (int)vals.size() - 1; i < j; ++i, --j) {
if (vals[i] != vals[j]) {
return false;
}
}
return true;
}
};