Hot100题解
必须掌握数据结构:[LeetCode力扣hot100]-C++常用数据结构_力扣hot 100 c++-CSDN博客
2.移动零✅
一、链表
1.相交列表
160. 相交链表 - 力扣(LeetCode)
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {set<ListNode *> visited;ListNode *temp=headA;while(temp!=nullptr){visited.insert(temp);temp=temp->next;}temp=headB;while(temp!=nullptr){if(visited.count(temp)){return temp;}else{temp=temp->next;}}return nullptr;}
};
二、二叉树
1.二叉树中序遍历
94. 二叉树的中序遍历 - 力扣(LeetCode)
左-中-右
vector用于返回结果,同时要借助栈(stack)这一数据结构(前序后序也同理)
栈S;
p= root;
while(p || S不空){while(p){p入S;p = p的左子树;}p = S.top 出栈;访问p;p = p的右子树;
}
从根节点开始,左树一直加到底。之后再最左子节点开始逐个遍历右边就行(因为左节点都放进去了)
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:vector<int> inorderTraversal(TreeNode* root) {stack<TreeNode*> stk;vector<int> ans;while(root||!stk.empty()){while(root){stk.push(root);root=root->left;}root=stk.top();stk.pop();ans.push_back(root->val);root=root->right;}return ans;}
};
2.二叉树最大深度
104. 二叉树的最大深度 - 力扣(LeetCode)
递归即可,max(左子树深度,右子树深度)+1;
class Solution {
public:int maxDepth(TreeNode* root) {if(root==nullptr){return 0;}else{return max(maxDepth(root->left),maxDepth(root->right))+1;}}
};
3.翻转二叉树
226. 翻转二叉树 - 力扣(LeetCode)
递归
class Solution {
public:TreeNode* invertTree(TreeNode* root) {if(root==nullptr){return nullptr;}TreeNode* left=invertTree(root->left);TreeNode* right=invertTree(root->right);root->right=left;root->left=right;return root;}
};
三、栈
1.有效的括号
20. 有效的括号 - 力扣(LeetCode)
有点像模拟,处理三种括号的左右情况.几个if-else分支即可解决。
class Solution {
public:bool isValid(string s) {stack<char> t;if(s.size()==0){return true;}for(int i=0;i<s.size();i++){if(s[i]=='{'){t.push(s[i]);}else if(s[i]=='('){t.push(s[i]);}else if(s[i]=='['){t.push(s[i]);}else if(s[i]==')'){if(t.empty() ||t.top()!='('){return false;}else{t.pop();}}else if(s[i]=='}'){if(t.empty() ||t.top()!='{'){return false;}else{t.pop();}}else if(s[i]==']'){if(t.empty() ||t.top()!='['){return false;}else{t.pop();}}}//最后对栈做一个非空为错的判定if(t.empty()){return true;}else{return false;}}
};