【LEETCODE】114-Flatten Binary Tree to Linked List

来源:互联网 发布:画图软件图标 编辑:程序博客网 时间:2024/05/22 03:25

Given a binary tree, flatten it to a linked list in-place.

For example,

Given

         1

        / \

       2   5

      / \   \

     3   4   6


The flattened tree should look like:

   1

    \

     2

      \

       3

        \

         4

          \

           5

            \

             6


参考:

http://chaoren.is-programmer.com/posts/42713.html


# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def flatten(self, root):        """        :type root: TreeNode        :rtype: void Do not return anything, modify root in-place instead.        """                while root:                        if root.left:                 p=root.left                while p.right:                    p=p.right              #p左child的最低端的右child                p.right=root.right         #把root.right放到p的右child                root.right=root.left       #把root.left移到root.right                root.left=None             #root.left变为空            root=root.right                #root移动到右child        return root            





0 0
原创粉丝点击