[Leetcode]Binary Tree Inorder Traversal
来源:互联网 发布:ubuntu内核是什么 编辑:程序博客网 时间:2024/05/17 23:29
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?
树的中序遍历~ 先来个递归解法~
class Solution: # @param root, a tree node # @return a list of integers def inorderTraversal(self, root): if root is None: return [] self.res = [] self.helper(root) return self.res def helper(self, root): if root is None: return self.helper(root.left) self.res.append(root.val) self.helper(root.right)非递归解法如下~
class Solution: # @param root, a tree node # @return a list of integers def inorderTraversal(self, root): if root is None: return [] stack = []; res = [] while stack or root != None: if root != None: stack.append(root) root = root.left else: root = stack.pop() res.append(root.val) root = root.right return res
还有一种非递归解法,是用常数空间,叫Morris Traversal~可以参考一下这篇文章:http://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html
找时间再好好看看好了~
0 0
- LeetCode: Binary Tree Inorder Traversal
- [LeetCode]Binary Tree Inorder Traversal
- LeetCode Binary Tree Inorder Traversal
- [Leetcode] Binary Tree Inorder Traversal
- Leetcode: Binary Tree Inorder Traversal
- LeetCode Binary Tree Inorder Traversal
- LeetCode : Binary Tree Inorder Traversal
- [Leetcode] Binary Tree Inorder Traversal
- 【leetcode】Binary Tree Inorder Traversal
- [LeetCode]Binary Tree Inorder Traversal
- Leetcode: Binary Tree Inorder Traversal
- [leetcode]Binary Tree Inorder Traversal
- LeetCode-Binary Tree Inorder Traversal
- Leetcode Binary Tree Inorder Traversal
- [leetcode] Binary Tree Inorder Traversal
- LeetCode - Binary Tree Inorder Traversal
- [LeetCode] Binary Tree Inorder Traversal
- LeetCode | Binary Tree Inorder Traversal
- js焦点 显示不同表单
- 面向对象--类与类之间的几种关系
- IE圆角支持
- 设计模式大全
- 线程间操作无效: 从不是创建控件“xx”的线程访问它
- [Leetcode]Binary Tree Inorder Traversal
- Mac下 升级 php+apache
- Activiti工作流引擎使用
- hdu 2066 一个人的旅行(迪杰斯特拉 && floyd)
- 战略游戏(stragedi)
- 追逐自己的梦想----------辅助制作第十四课:给出自动打怪和技能打怪的源码
- sql 删除记录中的空格方法
- GitHub上最火的74个Android开源项目
- ubuntu server 14.04 LTS 设置root密码-陈科肇