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
"""

以下是我的代码:

# 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 None
        node = root
        nodelist = []
        if node.right:
            nodelist.append(node.right)
        if node.left:
            nodelist.append(node.left)
        while nodelist:
            n = nodelist[-1]
            nodelist.pop()
            if n.right:
                nodelist.append(n.right)
            if n.left:
                nodelist.append(n.left)
            node.left = None
            node.right = n
            node = n
原文地址:https://www.cnblogs.com/mangmangbiluo/p/10691764.html