144 前序遍历
leetcode
递归版
/**
* 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 {
private:
void preorder(TreeNode* root, vector<int>& ans) {
if (!root)
return;
ans.push_back(root->val);
preorder(root->left, ans);
preorder(root->right, ans);
}
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
preorder(root, ans);
return ans;
}
};
迭代版
/**
* 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> ans;
if(!root)
return ans;
// 用栈模拟递归
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* cur = stk.top();
stk.pop();
ans.push_back(cur->val);
// 注意:这里一定要先压入右节点,再压入左节点(FILO)
if(cur->right) stk.push(cur->right);
if(cur->left) stk.push(cur->left);
}
return ans;
}
};