码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode--114. Flatten Binary Tree to Linked List

时间:2017-09-02 09:37:26      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:问题   时间   nts   like   rsa   bin   init   边界条件   problems   

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

标签:问题   时间   nts   like   rsa   bin   init   边界条件   problems   

原文地址:http://www.cnblogs.com/shihuvini/p/7465580.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!