题目描述
求给定的二叉树的前序遍历。
例如:
给定的二叉树为{1,#,2,3},
12/3
返回:[1,2,3].
备注;用递归来解这道题太没有新意了,可以给出迭代的解法么?
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型vector
*/
vector<int> preorderTraversal(TreeNode* root) {
// write code here
vector <int> res;
stack<TreeNode*> s;
if (root==NULL){
return res;
}
s.push(root);
while (!s.empty())
{
TreeNode *cur=s.top();
s.pop();
res.push_back(cur->val);
if (cur->right!=NULL)
s.push(cur->right);
if (cur->left !=NULL)
s.push(cur->left);
}
return res;
}
};