94、Binary Tree Inorder Traversal
2015-11-27 10:09
381 查看
题目:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree
return
Note: Recursive solution is trivial, could you do it iteratively?
解题思路:
迭代法中序遍历。
python版本:
c++版本:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree
{1,#,2,3},
1 \ 2 / 3
return
[1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
解题思路:
迭代法中序遍历。
python版本:
class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ def goAlongLeft(x,s): while(x): s.append(x) x = x.left stack,res = [],[] x = root while(True): goAlongLeft(x,stack) if(len(stack)==0):break x = stack.pop() res.append(x.val) x = x.right return res
c++版本:
class Solution { public: void goAlongLeft(TreeNode *x,stack<TreeNode *>&s){ while(x){ s.push(x); x = x->left; } } vector<int> inorderTraversal(TreeNode* root) { TreeNode *x = root; vector<int> res; stack<TreeNode *>s; while(true){ goAlongLeft(x,s); if(s.empty())break; x = s.top();s.pop(); res.push_back(x->val); x = x->right; } return res; } };
相关文章推荐
- 计算机视觉进展二十年 (1995~2015)
- APP接口开发之开始上路
- 在PHP代码中经常能看到一些类似PG(), EG()之类的函数,他们都是PHP中定义的宏,这系列宏主要的作用是解决线程安全所写的全局变量包裹宏, 如$PHP_SRC/main/php_globals.
- 《利用python进行数据分析》读书笔记--第三章 ipython使用
- 酷派品牌重塑,任重而道远
- count and say leetcode java
- java事务处理(jdbc)
- c++对ip和端口的处理
- tab选项卡切换效果
- 第二十四课
- 将App打包上传到AppStore
- WCF大数据量传输配置
- MySQL的查询缓存机制基本学习教程
- jquerymobile API
- python中list的append和extends的区别
- 开发基于CXF的 RESTful WebService web 项目 webservice发布
- Length of last word leetcode java
- 33.c/c++程序员面试宝典-函数重载
- Hadoop Problem
- iPhone5s 换电池、修右上角翘起的悲催过程