zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    bstToDoublyList
    Springboot系列1_什么是Springboot
    servlet总结
    JavaFx开发桌面软件
    在Emacs中使用plantuml画UML图
    IIS7.0上传文件限制的解决方法
    开源免费的天气预报接口API以及全国所有地区代码(国家气象局提供)
    如何得到天气情况?在那个接口获取?
    Windows Update 时出现8024402C的错误
    OC中copy的使用
  • 原文地址:https://www.cnblogs.com/shihuvini/p/7465580.html
Copyright © 2011-2022 走看看