[LeetCode] 114. 二叉树展开为链表

Posted powercai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 114. 二叉树展开为链表相关的知识,希望对你有一定的参考价值。

题目链接 : https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/

题目描述:

给定一个二叉树,原地将它展开为链表。

示例:

例如,给定二叉树

    1
   /   2   5
 / \   3   4   6

将其展开为:

1
   2
       3
           4
               5
                   6

思路:

其实对于这种题目,递归不太好想的,可以有个取巧的方法,就是把树转列表,因为结果是按照前序遍历的,所以有:

def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        if not root:return root
        d = []
        def helper(root):
            if not root:
                return 
            d.append(root.val)
            helper(root.left)
            helper(root.right)
        helper(root)
        i = 1 
        root.left = None
        p = root
        while i < len(d):
            p.right = TreeNode(d[i])
            p = p.right
            i += 1

上面做法属于作弊过的,

思路一: 递归, 类似后序遍历

思路二: 迭代,

直接看代码,很容易理解,但是不容易想!

代码:

思路一:

def flatten(self, root: TreeNode, pre = None) -> 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)

java

class Solution 
    public void flatten(TreeNode root) 
        helper(root, null);
    

    private TreeNode helper(TreeNode root, TreeNode pre) 
        if (root == null) return pre;
        pre = helper(root.right, pre);
        pre = helper(root.left, pre);
        root.right = pre;
        root.left = null;
        pre = root;
        return pre;
    

思路二:

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

java

class Solution 
    public void flatten(TreeNode root) 
      TreeNode cur = root;
        while (cur != null) 
            if (cur.left != null) 
                TreeNode p = cur.left;
                while (p.right != null) p = p.right;
                p.right = cur.right;
                cur.right = cur.left;
                cur.left = null;
            
            cur = cur.right;
        
    

?

以上是关于[LeetCode] 114. 二叉树展开为链表的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 114. 二叉树展开为链表(dfs)

[LeetCode] 114. 二叉树展开为链表 ☆☆☆(深度遍历)

[LeetCode] 114. 二叉树展开为链表

LeetCode(114): 二叉树展开为链表

LeetCode第114题—二叉树展开为链表—Python实现

Leetcode No.114 二叉树展开为链表