【Leetcode】【python】Binary Tree Inorder Traversal
来源:互联网 发布:网络保险产品 编辑:程序博客网 时间:2024/06/07 20:42
题目大意
中序遍历一个二叉树
挑战:不用递归只用迭代做
解题思路
递归简单
迭代:参考
我们使用一个栈来解决问题。步骤如下:
一,我们将根节点1入栈,如果有左孩子,依次入栈,那么入栈顺序为:1,2,4。由于4的左子树为空,停止入栈,此时栈为{1,2,4}。
二,此时将4出栈,并遍历4,由于4也没有右孩子,那么根据中序遍历的规则,我们显然应该继续遍历4的父亲2,情况是这样。所以我们继续将2出栈并遍历2,2存在右孩子,将5入栈,此时栈为{1,5}。
三,5没有孩子,则将5出栈并遍历5,这也符合中序遍历的规则。此时栈为{1}。
四,1有右孩子,则将1出栈并遍历1,然后将右孩子3入栈,并继续以上三个步骤即可。
栈的变化过程:{1}->{1,2}->{1,2,4}->{1,2}->{1}->{1,5}->{1}->{}->{3}->{3,6}->{3}->{}->{7}->{}。
代码
递归
class Solution(object): def generate(self, root, result): if root.left: self.generate(root.left, result) result.append(root.val) if root.right: self.generate(root.right, result) ''' 可以简化为如下答案 if root: self.inorder(root.left, list) list.append(root.val) self.inorder(root.right, list) ''' def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] result = [] self.generate(root, result) return result
迭代
class Solution: # @param root, a tree node # @return a list of integers def iterative_inorder(self, root, list): stack = [] while root or stack: if root: stack.append(root) root = root.left else: root = stack.pop() list.append(root.val) root = root.right return list def inorderTraversal(self, root): list = [] self.iterative_inorder(root, list) return list
递归(极简代码)
class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] else: return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
总结
- Python中:[1]+[2]+[3] = [1,2,3]
阅读全文
0 0
- 【LeetCode with Python】 Binary Tree Inorder Traversal
- 【LeetCode】【Python】Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal Leetcode Python
- 【Leetcode】【python】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
- Windows下安装Nexus OSS 3.4.0
- 北美CS求学找工指南
- 建站的原型图是什么意思?
- 10款优秀的产品包装设计欣赏!
- QQ2018安全问题介绍
- 【Leetcode】【python】Binary Tree Inorder Traversal
- 92. Reverse Linked List II
- yx:反射、注解
- oracle 复杂操作
- [Leetcode][二叉树]相关题目汇总/分析/总结
- 管理 Machine
- 消除序列中的重复
- Django建教育平台(一)--搭建环境,新建项目
- 在一个字符串中找到第一个只出现一次的字符