leetcode-94-Binary Tree Inorder Traversal
2015-06-21 23:08
471 查看
Binary Tree Preorder Traversal
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].
/** * 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>v; v.clear(); stack<TreeNode*>s; TreeNode* x; s.push(root); if(!root) return v; while(!s.empty()){ x=s.top(); v.push_back(x->val); s.pop(); if(x->right) s.push(x->right); if(x->left) s.push(x->left); } return v; } }; class Solution { //先序遍历 递归 public: vector<int>v; vector<int> preorderTraversal(TreeNode* root) { v.clear(); if(!root) return v; pre(root); return v; } void pre(TreeNode* p){ if(!p) return; v.push_back(p->val); pre(p->left); pre(p->right); } };
相关文章推荐
- 团队作业-第5周-测试与调试
- cocos2d-x核心类剖析-coco2d-x触屏实现机制
- c++学习-数组
- 《人,绩效和职业道德》读后感
- Android获取手机信息大全
- 2015062103 - 思考追求
- cocos2d-x核心类剖析-cocos2d-x定时器机制
- java基础—File类——获取C盘下的隐藏目录文件名称
- Java设计模式之单例模式
- HDU2033 人见人爱A+B
- 消息提醒、带声音提示、托盘图标闪烁
- HDU2033 人见人爱A+B 分类: ACM 2015-06-21 23:05 13人阅读 评论(0) 收藏
- RabbitMQ源码解析前奏--AMQP协议
- 初解DLL基本知识
- Debian Jessie 安装 迅雷(Xware)
- cocos2d-x核心类剖析-cocos2d-x内存管理机制
- 安卓中bundle的使用
- org.apache.jasper.JasperException: Unable to compile class for JSP 解决方法
- [xcode-warning]Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0
- Qt使用ui时,也可以使用栈对象