leetcode--114. Flatten Binary Tree to Linked List

Posted Shihu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode--114. Flatten Binary Tree to Linked List相关的知识,希望对你有一定的参考价值。

1、问题描述

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1
        /        2   5
      / \        3   4   6

The flattened tree should look like:

   1
         2
             3
                 4
                     5
                         6

Hints:

If you notice carefully in the flattened tree, each node‘s right child points to the next node of a pre-order traversal.

2、边界条件:无

3、思路:从示例可以看出,变成list之后是原来的先序遍历结果。那么就采用先序遍历把treenode转为list,再转为树。

4、代码实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        List<TreeNode> result = new ArrayList<>();
        preOrder(result, root);
        TreeNode dummy = new TreeNode(0);
        dummy.right = root;
        TreeNode newTree = dummy;
        for (int i = 0; i < result.size(); i++) {
            newTree.right = result.get(i);
            newTree.left = null;
            newTree = newTree.right;
        }
        root = dummy.right;
    }

    public void preOrder(List<TreeNode> result, TreeNode root) {
        if (root == null) {
            return;
        }
        result.add(root);
        preOrder(result, root.left);
        preOrder(result, root.right);
    }
}

方法二

My short post order traversal Java solution for share
private TreeNode prev = null;

public void flatten(TreeNode root) {
    if (root == null)
        return;
    flatten(root.right);//先把右子树flatten,prev=root.right
    flatten(root.left);//再把左子树flatten
    root.right = prev;//左子树的最右边是首先flatten的,所以就挂接了prev=root.right
    root.left = null;
    prev = root;
}

 

5、时间复杂度:O(N),空间复杂度:O(N)

6、api


以上是关于leetcode--114. Flatten Binary Tree to Linked List的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 114. Flatten Binary Tree to Linked List

leetcode--114. Flatten Binary Tree to Linked List

LeetCode 114. Flatten Binary Tree to Linked List

Leetcode 114, Flatten Binary Tree to Linked List

LeetCode-114-Flatten Binary Tree to Linked List

LeetCode 114 Flatten Binary Tree to Linked List