【Question】
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?
就是先序遍历的非递归实现
/**
* 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) {
TreeNode *p;
stack<TreeNode*> sta;
vector<int> vec;
p=root;
while(p!=NULL||!sta.empty())
{
while(p!=NULL)
{
vec.push_back(p->val);
sta.push(p);
p=p->left;
}
if(!sta.empty())
{
p=sta.top();
sta.pop();
p=p->right;
}
}
return vec;
}
};