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
return
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的用法
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的用法
相关文章推荐
- C++中虚函数的作用
- c++面向对象编程补充(一) 重载 覆盖 隐藏区别
- c++ 加载so动态库中的资源
- c++模板递归单例模式进阶版本
- c++面向对象编程(五)--高级 命名空间
- c++类的构造函数详解
- 替换空格(c语言完整版程序)
- 二叉树用C++实现
- 在C++中,有哪4个与类型转换符相关的关键字?这些关键字各有什么特点,在什么场合下使用?
- C++控制台显示日期时间和坐标排列
- C++时间与字符串转换
- 双链表的C语言实现
- C++20、友元类
- 循环链表的C语言实现
- 《C++ Primer Plus》第6章 学习笔记
- 《C++ Primer Plus》第5章 循环和关系表达式 学习笔记
- 细说线程函数
- 《C++ Primer Plus》第4章 学习笔记
- 指针与C++基本原理
- C++中的自动存储、静态存储和动态存储