leetcode 94. Binary Tree Inorder Traversal-中序遍历|递归|非递归
2016-05-23 16:03
411 查看
原题链接:94. Binary Tree Inorder Traversal
【思路-Java、Python】
非递归实现用到了栈,以[1,2,3,4,5,null,6]为例,下图模拟了这个过程
cases passed. Runtime: 3
ms Your runtime beats 0.60% of javasubmissions.
cases passed. Runtime: 52
ms Your runtime beats 9.94% of pythonsubmissions.
【补充非递归实现-Java、Python】
67 / 67 test
cases passed. Runtime: 1
ms Your runtime beats 62.04% of javasubmissions.
cases passed Runtime: 56
ms Your runtime beats 5.74% of pythonsubmissions.
挑战更多:
【思路-Java、Python】
非递归实现用到了栈,以[1,2,3,4,5,null,6]为例,下图模拟了这个过程
public class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); while(true) { while (root != null) { stack.add(root); root = root.left; } if (stack.isEmpty()) break; root = stack.pop(); res.add(root.val); root = root.right; } return res; } }67 / 67 test
cases passed. Runtime: 3
ms Your runtime beats 0.60% of javasubmissions.
class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ stack = [] res = [] while 1 : while root : stack.append(root) root = root.left if not stack : break root = stack.pop() res.append(root.val) root = root.right return res67 / 67 test
cases passed. Runtime: 52
ms Your runtime beats 9.94% of pythonsubmissions.
【补充非递归实现-Java、Python】
public class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); dfs(root, res); return res; } public void dfs(TreeNode root, List<Integer> res) { if (root == null) return; dfs(root.left, res); res.add(root.val); dfs(root.right, res); } }
67 / 67 test
cases passed. Runtime: 1
ms Your runtime beats 62.04% of javasubmissions.
class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res = [] def dfs(root,res) : if not root : return dfs(root.left, res) res.append(root.val) dfs(root.right, res) dfs(root,res) return res67 / 67 test
cases passed Runtime: 56
ms Your runtime beats 5.74% of pythonsubmissions.
挑战更多:
leetcode 230. Kth Smallest Element in a BST-递归|非递归
相关文章推荐
- 30 不重复的三位数
- 安装与配置 Elasticsearch
- 权利的游戏这部片子很现实的!
- [置顶] 实时监测蓝牙状态的Demo
- ecshop二次开发--视频上传
- MT6628_MT6620如何禁止soft-mute feature
- 面试题23
- javascript类学习(一)——构造器与原型链实现简单的继承
- Redis系列学习笔记3 散列
- 文件夹或者文件比对工具 Beyond Compare
- 个人优秀博客集合
- web服务器之iis,apache,tomcat三者之间的比较
- 二叉树--深度
- centos 7 安装与配置docker
- 文件夹或者文件比对工具 Beyond Compare
- db file sequential read事件
- vivado保存debug波形
- iOS 多线程 GCD
- json解析总结
- C++内置类型的机器实现