题目:

     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]