题解 | #二叉树的前序遍历#
二叉树的前序遍历
https://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635
递归
class Solution {
public:
vector<int> ans;
vector<int> preorderTraversal(TreeNode* root) {
dfs(root);
return ans;
}
void dfs(TreeNode* root) {
if (!root) return;
ans.push_back(root->val);
dfs(root->left);
dfs(root->right);
}
};
迭代
/**
* 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) {
vector<int> res;
stack<TreeNode*> stk;
while (root || stk.size()) {
// 遍历所有左子树
while(root) {
res.push_back(root->val); // 把当前结点值存入答案
stk.push(root); // 把所有root压入栈
root = root->left; // 左边
}
// 遍历完左子树之后直接变就可以遍历右子树
root = stk.top()->right; // 回溯到栈顶然后直接遍历右边
stk.pop(); // 弹出
}
return res;
}
};
#二叉树的前序遍历#