​LeetCode 144 ​

题目的意思就是不用递归的方法输出先序遍历

其实递归本质上是在利用栈的性质,每次递归都是将一个函数压入栈中。
所以我们可以用循环和栈模拟递归

class Solution {
public:
TreeNode* s[100005];
vector<int> ans;
int tag=0;
vector<int> preorderTraversal(TreeNode* root) {
if(root==NULL) return ans;
s[tag++]=root;
TreeNode* term;
while(tag>0)
{
term = s[tag-1];
if(s[tag-1]->val!=-999999)
ans.push_back(s[tag-1]->val);
(*s[tag-1]).val=-999999;

if(term->left!=NULL&&term->left->val!=-999999)
{s[tag++]=term->left;continue;}


if(term->right!=NULL&&term->right->val!=-999999)
{s[tag++]=term->right;continue;}
tag--;

}
return ans;
}
};