zoukankan      html  css  js  c++  java
  • 42.Flatten Binary Tree to Linked List

    Level:

      Medium

    题目描述:

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

    For example, given the following tree:

        1
       / 
      2   5
     /    
    3   4   6
    

    The flattened tree should look like:

    1
     
      2
       
        3
         
          4
           
            5
             
              6
    

    思路分析:

      思路一:将二叉树转换为链表,我们可以先序遍历二叉树将节点保存起来,然后依次访问节点构造链表。

      思路二:不使用额外的空间,在遍历的过程中构造链表。

    代码:

    代码一

    /**public class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        public TreeNode(int x){
            val=x;
        }
    }*/
    public class Solution{
        List<TreeNode>list=new ArrayList<>();
        public void flatten(TreeNode root){
            if(root==null)
                return;
            pre(root);
            for(int i=0;i<list.size()-1;i++){
                list.get(i).left=null;
                list.get(i).right=list.get(i+1);
            }
        }
        public void pre(TreeNode root){
            if(root!=null){
                list.add(root);
                pre(root.left);
                pre(root.right);
            }
        }
    }
    

    代码二

    public class Solution{
        TreeNode pre=null;
        public void flatten(TreeNode root){
            if(root==null)
                return;
            flatten(root.right);
            flatten(root.left);
            root.right=pre;
            root.left=null;
            pre=root;
        }
    }
    
  • 相关阅读:
    熟悉常用的Linux操作
    Python基础综合练习
    简易c语言文法
    词法分析程序
    组合数据类型综合练习
    综合练习:词频统计
    词法分析程序2
    我对编译原理的理解
    【分享】博客美化(6)为你的博文自动添加目录
    python爬虫的基本思路
  • 原文地址:https://www.cnblogs.com/yjxyy/p/11079954.html
Copyright © 2011-2022 走看看