题目描述
给定一个二叉树,返回它的 前序 遍历。
示例
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
思路1
递归很简单。
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorder(root, res);
return res;
}
void preorder(TreeNode* root, vector<int>& res){
if (!root) return;
res.push_back(root->val);
preorder(root->left, res);
preorder(root->right, res);
}
};
思路2
迭代。
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> s;
while (root || !s.empty()){
while (root){
res.push_back(root->val);
s.push(root);
root = root->left;
}
if (!s.empty()){
root = s.top();
s.pop();
root = root->right;
}
}
return res;
}
};