File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- 学习笔记
1+ 学习笔记
2+
3+ 1.熟记二叉树遍历模板,并使用(前中后序,bfs dfs)
4+ 2.二叉树的遍历一般用递归来实现即可,如果一定要用迭代来实现,那么可以考虑引用一个栈,将未遍历的节点存入栈中这种方式来实现。
5+ 3.大顶堆:根节点大于所有子节点。
6+ 小顶堆:根节点小于所有子节点。
7+ 4.对于堆的使用:可以利用堆来找出 第K个最大/最小的值。
8+ 5.堆是一种比较抽象的数据结构,二叉堆不代表堆,只是堆的一种。
9+ 6.二叉堆是堆中实现起来较为简单的一种堆。
Original file line number Diff line number Diff line change 1+ // 递归
2+ class Solution {
3+ public:
4+ void preOrder (TreeNode* root,std::vector<int > &result)
5+ {
6+ if (root == nullptr )
7+ return ;
8+ result.push_back (root->val );
9+ preOrder (root->left ,result);
10+ preOrder (root->right ,result);
11+ }
12+ vector<int > preorderTraversal (TreeNode* root) {
13+ std::vector<int > result;
14+
15+ preOrder (root,result);
16+
17+ return result;
18+ }
19+ };
20+ // 迭代
21+ class Solution {
22+ public:
23+ vector<int > preorderTraversal (TreeNode* root) {
24+ std::vector<int > result;
25+ std::stack<TreeNode*> st;
26+
27+ TreeNode* node = root;
28+ while (1 )
29+ {
30+ if (node != nullptr )
31+ {
32+ result.push_back (node->val );
33+ if (node->right != nullptr )
34+ st.push (node->right );
35+ node = node->left ;
36+ }
37+ else if (st.empty ())
38+ {
39+ break ;
40+ }
41+ else
42+ {
43+ node = st.top ();
44+ st.pop ();
45+ }
46+ }
47+ return result;
48+ }
49+ };
Original file line number Diff line number Diff line change 1+ // 利用map来实现,很耗时
2+ class Solution {
3+ public:
4+ bool isAnagram (string s, string t) {
5+ if (s.length () != t.length ())
6+ return false ;
7+
8+ std::map<char ,int > statisticMap1;
9+ statisticMap1.clear ();
10+ for (int i = 0 ; i < s.length (); i++)
11+ {
12+ if (statisticMap1.find (s[i]) == statisticMap1.end ())
13+ statisticMap1[s[i]] = 1 ;
14+ else
15+ statisticMap1[s[i]]++;
16+ }
17+ // std::map<char,int> statisticMap2;
18+ // statisticMap2.clear();
19+ for (int i = 0 ; i < t.length (); i++)
20+ {
21+ if (statisticMap1.find (t[i]) == statisticMap1.end ())
22+ statisticMap1[t[i]] = 1 ;
23+ else
24+ statisticMap1[t[i]]--;
25+ }
26+ std::map<char ,int >::iterator iter = statisticMap1.begin ();
27+ for (;iter != statisticMap1.end ();++iter)
28+ {
29+ if (iter->second != 0 )
30+ return false ;
31+ }
32+ return true ;
33+ }
34+ };
35+ // 用数组实现的hash,效率要比上一个快
36+ class Solution {
37+ public:
38+ bool isAnagram (string s, string t) {
39+ if (s.length () != t.length ())
40+ return false ;
41+
42+ int hash[26 ] = {0 };
43+
44+ for (char n : s)
45+ hash[n - ' a' ]++;
46+ for (char n : t)
47+ hash[n - ' a' ]--;
48+ for (int n : hash)
49+ {
50+ if (n != 0 )
51+ return false ;
52+ }
53+ return true ;
54+ }
55+ };
You can’t perform that action at this time.
0 commit comments