题目
迭代思路
本质上是在模拟递归,因为在递归的过程中使用了系统栈。
- 先将根结点放入栈
- 每次弹出栈顶元素存入答案
- 先将右节点存入栈,再将左节点存入栈
代码(首刷自解)
递归
class Solution {
public:
vector<int> ans;
vector<int> preorderTraversal(TreeNode* root) {
if(!root)
return ans;
traverse(root);
return ans;
}
void traverse(TreeNode* root) {
if(!root)
return;
ans.push_back(root->val);
traverse(root->left);
traverse(root->right);
}
};
迭代
用栈实现,先插右再插左
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if(!root)
return {};
stack<TreeNode*> q; // 栈
vector<int> ans;
q.push(root);
while(!q.empty()) {
auto front = q.top();
q.pop();
ans.push_back(front->val);
if(front->right)
q.push(front->right);
if(front->left)
q.push(front->left);
}
return ans;
}
};
迭代,统一写法
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if(root) st.push(root);
while(!st.empty()) {
root = st.top();
if(root) {
st.pop();
if(root->right) st.push(root->right);
if(root->left) st.push(root->left);
st.push(root);
st.push(nullptr);
} else {
st.pop();
root = st.top();
res.push_back(root->val);
st.pop();
}
}
return res;
}
};
代码(8.5 二刷看解析 GO)
GO还是不太熟悉,今天用模板解法做了一遍,巩固一下。
func preorderTraversal(root *TreeNode) []int {
stack := []*TreeNode{}
res := []int{}
if root != nil {
stack = append(stack, root)
}
for len(stack) > 0 {
root = stack[len(stack) - 1] // 栈顶
if root != nil {
stack = stack[:len(stack) - 1] // 出栈
if root.Right != nil {
stack = append(stack, root.Right)
}
if root.Left != nil {
stack = append(stack, root.Left)
}
stack = append(stack, root)
stack = append(stack, nil)
} else {
stack = stack[:len(stack) - 1] // 出栈
root = stack[len(stack)-1]
res = append(res, root.Val)
stack = stack[:len(stack) - 1] // 出栈
}
}
return res
}
递归
func preorderTraversal(root *TreeNode) []int {
res := []int{}
var preorder func(*TreeNode) // 必须先定义,因为下面用了递归
preorder = func(root *TreeNode) {
if root == nil {
return
}
res = append(res, root.Val)
preorder(root.Left)
preorder(root.Right)
}
preorder(root)
return res
}
代码(8.13 三刷自解)
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(!root)
return res;
stack<TreeNode*> sk;
sk.push(root);
while(!sk.empty()) {
auto top = sk.top();
sk.pop();
if(top) {
if(top->right) sk.push(top->right);
if(top->left) sk.push(top->left);
sk.push(top);
sk.push(nullptr);
} else {
res.push_back(sk.top()->val);
sk.pop();
}
}
return res;
}
};
代码(9.8 四刷自解)
迭代
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if(!root)
return {};
vector<int> res;
stack<TreeNode*> q;
q.push(root);
while(!q.empty()) {
auto front = q.top();
q.pop();
if(front) {
if(front->right) q.push(front->right);
if(front->left) q.push(front->left);
q.push(front);
q.push(nullptr);
} else {
front = q.top();
q.pop();
res.push_back(front->val);
}
}
return res;
}
};