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)

 另:递归(2)

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

 

posted @ 2019-07-14 20:19  oldby  阅读(149)  评论(0编辑  收藏  举报