Leetcode刷题记录——114. 二叉树展开为链表

Leetcode刷题记录——114. 二叉树展开为链表_第1张图片
栈初始化为[ROOT]
起初self.last指向空
随后弹出栈首
如果last不是空
则将弹出的东西付在last的右孩子

对弹出元素执行
按先右孩子后左孩子的顺序入栈
入栈后该孩子位置清空


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.queue = []
        self.last = None
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        if root == None:
            return None
        self.queue = [root]
        while self.queue != []:
            cur = self.queue.pop(-1)
            if self.last != None:
                self.last.right = cur
            self.last = cur
            if cur != None:
                self.func(cur)

    def func(self,node):
        if node == None:
            return None
        if node.right != None:
            self.queue.append(node.right)
            node.right = None
        if node.left != None:
            self.queue.append(node.left)
            node.left = None


        
        



你可能感兴趣的:(leetcode,python编程技巧)