解决DP问题时,需要先确定初始状态,然后确定如何转移状态,再编程进行求解。
前序遍历的迭代写法
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
while (root)
{
if (!root->left)
{
res.push_back(root->val);
root = root->right;
}
else
{
TreeNode* pre = root->left;
while (pre->right && pre->right != root) pre = pre->right;
if (pre->right) pre->right = 0, root = root->right;
else
{
pre->right = root;
res.push_back(root->val);
root = root->left;
}
}
}
return res;
}
使用一个字符减 ‘0’ 可以得到正确的int值。
调用sort函数排序时,可引入以下这样的一个比较函数,从而获得一个字典序的序列
static bool cmp(int a, int b) {
auto as = to_string(a), bs = to_string(b);
return as + bs < bs + as;
}
善用deque, 可以借此实现栈和队列。
class MyStack {
public:
deque<int> q;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q.push_back(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
q.pop_back();
return q.back();
}
/** Get the top element. */
int top() {
return q.back();
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
};
class MyQueue {
public:
deque<int> q;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
q.push_back(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int x = q.back();
q.pop_back();
return x;
}
/** Get the front element. */
int peek() {
return q.front();
}
/** Returns whether the queue is empty. */
bool empty() {
return q.empty();
}
};