Skip to the content.

leetcode [114] 二叉树展开为链表


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


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

例如,给定二叉树
    1
   / \
  2   5
 / \   \
3   4   6
将其展开为:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6
class Solution:
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        if root is None:
            return
        if root.right is None:
            root.right = root.left
            root.left = None
        if root.left is None:
            self.flatten(root.right)
            return
        self.flatten(root.left)
        self.flatten(root.right)
        left = root.left
        while left.right:
            left = left.right
        left.right = root.right
        root.right = root.left
        root.left = None