题目
分析
递归和迭代都需要理解,然后背下来。
二叉树的前序遍历指的是对于每个节点,都是按根、左、右这样的顺序遍历。
递归比较好理解,每次递归都是将根节点的值记录下来,然后遍历左节点、右节点。递归边界是遍历的节点为空。
迭代是用栈存节点,先存根节点,然后进入while循环,重复同一过程:先取栈顶(这轮循环的根节点)、存右节点、存左节点。先右后左取出来才是先左后右。栈空时说明没有节点了,返回结果。
代码
递归写法:
/**
* 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:
void preorder(TreeNode *root, vector<int> &res) {
if (root == nullptr) {
return;
}
res.push_back(root->val);
preorder(root->left, res);
preorder(root->right, res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorder(root, res);
return res;
}
};
迭代写法:
/**
* 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> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
if (root == nullptr) {
return result;
}
// 入栈顺序:中、右、左
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
result.push_back(node->val);
if (node->right) {
st.push(node->right);
}
if (node->left) {
st.push(node->left);
}
}
return result;
}
};