【Leetcode_总结】114. 二叉树展开为链表 - python

Q:

给定一个二叉树,原地将它展开为链表。

例如,给定二叉树

    1
   / \
  2   5
 / \   \
3   4   6

将其展开为:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/

思路:递归

代码:

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

class Solution:
    def flatten(self, root: 'TreeNode') -> 'None':
        """
        Do not return anything, modify root in-place instead.
        """
        if not root:
            return
        self.flatten(root.left)
        self.flatten(root.right)
        if root.left is not None:
            right = root.right
            root.right = root.left
            root.left = None
            node = root.right
            while(node.right is not None):
                node = node.right
            node.right = right

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/87876526