leetcode-114-二叉树展开为链表*

题目描述:

方法一:迭代

class Solution:
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        cur = root 
        while cur: 
            if cur.left: 
                p = cur.left 
                while p.right: 
                    p = p.right 
                p.right = cur.right 
                cur.right = cur.left 
                cur.left = None 
            cur = cur.right

 方法二:递归

class Solution:
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        def helper(root, pre): 
            if not root: 
                return pre # 记录遍历时候,该节点的前一个节点 
            pre = helper(root.right, pre) 
            pre = helper(root.left, pre) # 拼接 
            root.right = pre 
            root.left = None 
            pre = root 
            return pre 
        helper(root, None)

猜你喜欢

转载自www.cnblogs.com/oldby/p/11185508.html