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