Likou 114. Expand a binary tree into a linked list (python version)

Topic source: 114. Binary tree is expanded into a linked list
Topic: Give you the root node root of a binary tree, please expand it into a singly linked list:

  • The expanded singly linked list should also use TreeNode, where the right child pointer points to the next node in the linked list, and the left child pointer is always null.
  • The expanded singly linked list should be in the same preorder traversal order as the binary tree.
    insert image description here
    insert image description here
    Idea: Recursive Input a node root
    to the flatten function , then the binary tree rooted at root will be flattened into a linked list. How to flatten a tree into a linked list according to the title? The following process: 1. Flatten the left subtree and right subtree of the root . 2. Connect the right subtree of the root to the bottom of the left subtree, and then use the entire left subtree as the right subtree. What is more difficult to understand is the first step, how to level the left and right subtrees? According to the explanation of reference link 1, through the definition of the flatten function, the flatten function can be recursively called on the left and right subtrees of the root . (I don't quite understand why, and the friends who understand can discuss it together in the comment area...) Python code:



    insert image description here

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: 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:
            temp = root.left
            while (temp.right):
                temp = temp.right
            temp.right = root.right
            root.right = root.left
            root.left = None
        return root

insert image description here
Reference link: [Interview High-Frequency Questions] Expand a Binary Tree into a Linked List
Expand a Binary Tree into a Linked List (python)
[LeetCode 114] Expand a Binary Tree into a Linked List (Python)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324339213&siteId=291194637