您的位置:首页 > 编程语言 > Python开发

leetcode 114. Flatten Binary Tree to Linked List (Python版)

2016-01-23 22:37 411 查看
题目:
Given a binary tree, flatten it to a linked list in-place.
算法思路:
其实该题目就是二叉树前序遍历的变形
我代码沿用leetcode 144. Binary Tree Preorder Traversal
代码:
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:return []

stack = [root]
result = []

while len(stack) != 0:
tmp_root = stack.pop()
if tmp_root == None:continue

result.append(tmp_root)
stack.append(tmp_root.right)
stack.append(tmp_root.left)
return result

def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
result = self.preorderTraversal(root)
for i in range(1,len(result)):
result[i-1].left = None
result[i-1].right = result[i]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: