94. Binary Tree Inorder Traversal
来源:互联网 发布:java gc日志 编辑:程序博客网 时间:2024/05/16 08:10
题意:Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3],
1 \ 2 / 3
return [1,3,2].
思路:二叉树的中序遍历有递归和不递归两种方法,这两种方法都需要用到O(n)的时间和空间复杂度,当然还有一种方法:Morris Traversal方法遍历二叉树,这个方法需要稍多的时间复杂度,但是只需要O(1)的空间复杂度,先介绍一下普通方法。
参考代码:
递归方式:
def inorderTraversal1(self, root): res = [] self.helper(root, res) return resdef helper(self, root, res): if root: self.helper(root.left, res) res.append(root.val) self.helper(root.right, res)
栈的方式:
def inorderTraversal(self, root): res, stack = [], [] while 1: while root: stack.append(root) root = root.left if not stack: return res node = stack.pop() res.append(node.val) root = node.right
接下来就是Morris Traversal方法,这个方法的关键是找到对应节点的中序前驱结点,也就是该节点左子树的最右结点,让它指向该节点,这是用添加指针的方式代替了栈,具体做法可以看Morris Traversal。
def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ result, curr = [], root while curr: if curr.left is None: result.append(curr.val) curr = curr.right else: node = curr.left while node.right and node.right != curr: node = node.right if node.right is None: node.right = curr curr = curr.left else: result.append(curr.val) node.right = None curr = curr.right return result
0 0
- 94. Binary Tree Inorder Traversal
- 94.Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94.Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- CPU,内存,硬盘,指令之间的关系
- 1.1XAF框架开发视频教程-简单的订单管理实现过程,视频,提纲,及教程源码
- 调用startActivityForResult,onActivityResult无响应的问题
- hdu 5380 Travel with candy (单调队列)@
- Android Studio使用gradle-experimental构建NDK工程(无需Android.mk、Application.mk文件)
- 94. Binary Tree Inorder Traversal
- 计蒜客等差数列
- gitlab的安装和使用
- mysql dos命令 创建表单,选择数据库
- Mac Xcode空间清理
- Spring入门学习笔记第一课——spring简介以及包结构
- 防止表单重复提交
- 求某个数在数组中出现的次数超过数组的一半
- diy电脑硬件交流---日积月累