/** * Definition for singly-linked list with a random pointer. * struct ListNode { * int val; * ListNode *next, *random; * ListNode(int x) : val(x), next(NULL), random(NULL) {} * }; */ classSolution { public: ListNode *copyRandomList(ListNode *head){ if (!head) returnNULL; for (auto p = head; p;) { auto np = new ListNode(p->val); auto next = p->next; np->next = next; p->next = np; p = next; } for (auto p = head; p; p = p->next->next) { if (p->random) { p->next->random = p->random->next; } } auto dummy = new ListNode(-1); auto tail = dummy; for (auto p =head; p;) { tail = tail->next = p->next; p = p->next = p->next->next; } return dummy->next; } };
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classSolution { public: vector<vector<int>> printFromTopToBottom(TreeNode* root){ vector<vector<int>> res; queue<TreeNode*> q; if (!root) return res; q.push(root); q.push(nullptr); vector<int> level; while (q.size()) { auto t = q.front(); q.pop(); if (!t) { if (level.empty()) break; res.push_back(level); level.clear(); q.push(nullptr); continue; } level.push_back(t->val); if (t->left) q.push(t->left); if (t->right) q.push(t->right); } }
vector<vector<int>> printFromTopToBottom2(TreeNode* root){ vector<vector<int>> res; vector<int> level; queue<TreeNode*> q; if (!root) return res; q.push(root); while (q.size()) { int qs = q.size(); //必须赋值到局部变量 for (int i = 0; i < qs; ++i) { auto t = q.front(); q.pop(); level.push_back(t->val); if (t->left) q.push(t->left); if (t->right) q.push(t->right); } res.push_back(level); level.clear(); } } };
q.push_back(make_pair(0, root)); while (!q.empty()) { int n = q.size(); for (int i = 0; i < n; i++) { PIT p = q.top(); q.pop(); m[p.first].push_back(p.second.val); if (p.second->left) q.push_back(make_pair(p.first - 1, p.second->left)); if (p.second->right) q.push_back(make_pair(p.first - 1, p.second->right)); } } }