首页 > 编程语言 > 详细

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

时间:2016-01-24 19:54:34      阅读:177      评论:0      收藏:0      [点我收藏+]

题目:

     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]


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

原文:http://wdswds.blog.51cto.com/11139828/1737957

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!