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

  • 相关阅读:
    数据库被挂马3
    將目標網址轉換成HTML
    四步堵死3b3.org c.js注入
    GBK与UTF8编码选择与区分
    C#连Oracle数据库
    Session过期时间的四种设置方式
    怎么从内容页访问母板页
    Response.Charset与Response.ContentEncoding的区别
    CommandBehavior.CloseConnection的使用
    尽可能的使用强类型
  • 原文地址:https://www.cnblogs.com/shihuvini/p/7465580.html
Copyright © 2011-2022 走看看