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

  • 相关阅读:
    python CST中国标准时间格式转换
    pytest+报告插件
    getopt实现命令行
    初识Redis
    python list 切片及翻转的使用
    mysql中information_schema表
    获取两个字符串中最长的相同子串
    mongodb数据库备份
    VS2005下边不能使用target>remote tool解决方法
    wince LoadDriver tool
  • 原文地址:https://www.cnblogs.com/shihuvini/p/7465580.html
Copyright © 2011-2022 走看看