144. Binary Tree Preorder Traversal
2016-07-12 20:25
239 查看
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree
return
Note: Recursive solution is trivial, could you do it iteratively?
Subscribe to see which companies asked this question
非递归写法:
/**
* 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) {
vector<int> v1;
pretracel(root,v1);
return v1;
}
void pretracel(TreeNode* root, vector<int>&v1)
{
stack<TreeNode*> t1;
while(!t1.empty()||root)
{
while(root)
{
t1.push(root);
v1.push_back(root->val);
root=root->left;
}
if(!t1.empty())
{
TreeNode* temp=t1.top();
t1.pop();
root=temp->right;
}
}
return ;
}
};
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?
Subscribe to see which companies asked this question
/** * 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) { vector<int> v1; if(root==NULL) return v1; pretracel(root,v1); return v1; } void pretracel(TreeNode* root, vector<int>&v1) { if(root==NULL) return ; v1.push_back(root->val); if(root->left) pretracel(root->left,v1); if(root->right) pretracel(root->right,v1); return ; } };
非递归写法:
/**
* 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) {
vector<int> v1;
pretracel(root,v1);
return v1;
}
void pretracel(TreeNode* root, vector<int>&v1)
{
stack<TreeNode*> t1;
while(!t1.empty()||root)
{
while(root)
{
t1.push(root);
v1.push_back(root->val);
root=root->left;
}
if(!t1.empty())
{
TreeNode* temp=t1.top();
t1.pop();
root=temp->right;
}
}
return ;
}
};
相关文章推荐
- 欢迎使用CSDN-markdown编辑器
- 发送验证码倒计时、图片验证码
- Java Enum类的笔记
- (java)socket全双工长连接通信实例
- SSI与Velocity解析时的区别
- cocos2d-x lua中实现异步加载纹理
- asp.net mvc本地程序集和GAC的程序集冲突解决方法
- 分析索引效率
- liunx密码破译
- yii 框架的文件上传 (简单实现)
- txt报表IO流
- error while loading shared libraries: xxx.so.x" 错误的原因和解决办法
- MediaPlayer(音乐播放器)
- Activity的关闭返回指定页面
- 抽象布局
- URL网络通讯
- Android单选按钮RadioButton来看你选男还是女
- 【MySQL】常见的mysql 进程state
- 如何开栈
- 随机数的两道题