Description:
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
思路:
下面code中既有递归实现也有非递归实现。
Solution:
/**
* Definition for binary tree
* 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;
solve2(root,res);
return res;
}
private:
void solve(TreeNode *root,vector<int>& res)
{
if(root==NULL)return;
res.push_back(root->val);
if(root->left)solve(root->left,res);
if(root->right)solve(root->right,res);
return;
}
void solve2(TreeNode *root,vector<int>& res)
{
if(root==NULL)return;
stack<pair<TreeNode*,pair<int,int> > > s;
s.push(make_pair(root,make_pair(1,1)));
while(!s.empty())
{
pair<TreeNode*,pair<int,int> >& p1=s.top();
root=p1.first;
if(p1.second.first==0 && p1.second.second==0)
{
s.pop();
continue;
}
if(p1.second.first && p1.second.second)res.push_back(root->val);
if(p1.second.first)
{
p1.second.first=0;
if(root->left)
{
s.push(make_pair(root->left,make_pair(1,1)));
continue;
}
}
if(p1.second.second)
{
p1.second.second=0;
if(root->right)
{
s.push(make_pair(root->right,make_pair(1,1)));
continue;
}
}
}
}
};