144、Binary Tree Preorder Traversal
来源:互联网 发布:云计算的几种形式 编辑:程序博客网 时间:2024/04/30 10:15
题目:
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?
解题思路:前序遍历的迭代方式。
c++版本:
class Solution {public: void visitAlongLeft(TreeNode* x,stack<TreeNode*>&s,vector<int>& res){ while(x){ res.push_back(x->val); s.push(x->right); x = x->left; } } vector<int> preorderTraversal(TreeNode* root) { stack<TreeNode*> s; vector<int> res; //TreeNode *x = root; while(true){ visitAlongLeft(root,s,res); if(s.empty()) break; root = s.top();s.pop(); } return res; }};
python版本:
class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ def visitAlongLeft(x,s,res): while(x!=None): res.append(x.val) s.append(x) x = x.left s,res = [], [] while True: visitAlongLeft(root,s,res) if(len(s)==0):break root = s.pop() root = root.right return res
0 0
- [144]Binary Tree Preorder Traversal
- 144、Binary Tree Preorder Traversal
- 144Binary Tree Preorder Traversal
- 144 Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- 通达OA 办公系统(Office Anywhere)动态密码配置使用详解
- Java使用RandomAccessFile读写文件
- 秒杀多线程第八篇---经典线程同步 信号量Semaphore
- Spring-Task 定时任务
- hackthissite basic 1-11
- 144、Binary Tree Preorder Traversal
- Android Service常驻后台 守护程序
- 菜鸟学Java-----内部类1
- iOS 自定义声明及使用带参block
- myeclipse快捷键
- 找出安装后的位置
- easyui--tab 选项卡组件
- solr环境搭建(一)
- 设计模式(一)--简单工厂模式