您的位置:首页 > 编程语言 > C语言/C++

leetcode-144. Binary Tree Preorder Traversal c++

2016-07-06 20:27 417 查看
1、来源:144. Binary Tree Preorder Traversal

2、题目:

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?
3、我的代码:
/**
* 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) {
stack<TreeNode*> s;
vector<int> v;
if(root==NULL)
return v;
s.push(root);
while(!s.empty()){
TreeNode*p=s.top();
v.push_back(p->val);
s.pop();
if(p->right!=NULL){
s.push(p->right);
}
if(p->left!=NULL){
s.push(p->left);
}
}
return v;
}
};

4、参考:
    1)前序遍历

     2)vector的用法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: