【leetcode】114. Flatten Binary Tree to Linked List

题目如下:

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

For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6

The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

解题思路:递归,从左子树开始,找到最深的左边节点,然后依次令node.right = node.left,再把原先的node.right加到原先的node.left的最右叶子节点即可。

代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.
        """
        node = root
        if node != None and node.left == None and node.right == None:
            return
        elif node != None and node.left != None:
            self.flatten(node.left)
        if node != None and node.left != None and node.right == None:
            node.right = node.left
            node.left = None
        elif node != None and node.left != None and node.right != None:
            tmpNode = node.right
            node.right = node.left
            node.left = None
            while node.right != None:
                node = node.right
            node.right = tmpNode
            self.flatten(node.right)
        elif node != None and node.left == None and node.right != None:
            self.flatten(node.right)
        return root

 

posted @ 2019-08-22 17:30  seyjs  阅读(187)  评论(0编辑  收藏  举报