【Leetcode】【python】Binary Tree Preorder Traversal
来源:互联网 发布:淘宝借呗 编辑:程序博客网 时间:2024/06/06 08:14
题目大意
二叉树前序遍历
挑战:迭代解题
解题思路
递归简单
迭代思路:博客
1 / \ 2 3 / \ / \ 4 5 6 7
使用一个栈。步骤为:
一,先遍历节点1,并入栈,如果有左孩子,继续遍历并入栈,一直到栈为{1,2,4}。
二,开始弹栈,当栈顶元素为2时,弹出2,并检测2存在右孩子5,于是遍历5并入栈,此时栈为{1,5}。
三,弹出5,5没有左右孩子,继续弹栈,将1弹出后,栈为{}。
四,由于1存在右孩子,则继续按照以上步骤入栈出栈。{3, 6}->{7}->{},结束。
栈的状态变化:{1}->{1,2}->{1,2,4}->{1,2}->{1}->{1,5}->{1}->{}->{3}->{3,6}->{3}->{}->{7}->{}。
代码
递归
class Solution(object): def _preorderTraversal(self, root, result): if root: result.append(root.val) self._preorderTraversal(root.left, result) self._preorderTraversal(root.right, result) def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root == None: return [] result = [] self._preorderTraversal(root, result) return result
迭代
class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ ret = [] stack = [root] while stack: node = stack.pop() if node: ret.append(node.val) stack.append(node.right) stack.append(node.left) return ret
总结
阅读全文
0 0
- 【LeetCode with Python】 Binary Tree Preorder Traversal
- Leetcode -- Python -- Binary Tree Preorder Traversal
- leetcode [python] 【144】 Binary Tree Preorder Traversal
- 【Leetcode】【python】Binary Tree Preorder Traversal
- LeetCode Binary Tree Preorder Traversal
- 【LeetCode】Binary Tree Preorder Traversal
- Leetcode: Binary Tree Preorder Traversal
- Leetcode Binary Tree Preorder Traversal
- LeetCode:Binary Tree Preorder Traversal
- Leetcode: Binary Tree Preorder Traversal
- LeetCode:Binary Tree Preorder Traversal
- [LeetCode]Binary Tree Preorder Traversal
- [LeetCode] Binary Tree Preorder Traversal
- LeetCode | Binary Tree Preorder Traversal
- Leetcode: Binary Tree Preorder Traversal
- [LeetCode] Binary Tree Preorder Traversal
- LeetCode - Binary Tree Preorder Traversal
- LeetCode - Binary Tree Preorder Traversal
- uva679
- 【文献阅读】dropout distillation
- Vue进阶-入门
- Making the Grade (bzoj1592)
- unity角色摄像机实际坐标变了,但是不移动的问题
- 【Leetcode】【python】Binary Tree Preorder Traversal
- 搭建简单的http服务器
- 计算机视觉小实例 No.4 车牌定位(二)
- 08020000
- Spring日志记录+线程池
- python正则表达式
- 【Leetcode】【python】Binary Tree Postorder Traversal
- C++ 中为什么模板不支持分离编译?
- JSTL 标签详解