114. 二叉树展开为链表

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

解法一:后序

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:   
            old_right = root.right  #记录右子
            root.right = root.left  #插入
            root.left = None    #记得将左子置空
            work = root.right
            while work.right:   #找到最右下结点
                work = work.right
            work.right = old_right  #接上原右子
        #不用返回

最后更新于