题解 | #二叉树的序列化#

二叉树的序列化

http://www.nowcoder.com/practice/d6425eab86fc402085f9fafc0db97cc2

直接使用sout会超时,需要使用StringBuilder

import java.util.*;
public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
        String[] s1=input.readLine().split(" ");      
        Queue<Tnode> nodes=new LinkedList<>();
        int num=Integer.parseInt(s1[0]);
        Tnode root=creatTN(input);
        StringBuilder sb = new StringBuilder();
        preOrder(root,sb);
        System.out.println(sb);
        sb.delete(0,sb.length());
        nodes.offer(root);
        cxOrder(nodes,sb); 
        System.out.println(sb);
        input.close();
    }
    //创建二叉树
    public static Tnode creatTN(BufferedReader input) throws IOException{
        String[] s=input.readLine().split(" ");
        Tnode node=new Tnode(Integer.parseInt(s[0]));
        if(Integer.parseInt(s[1])!=0){
            node.l=creatTN(input);
        }
        if(Integer.parseInt(s[2])!=0){
            node.r=creatTN(input);
        }
        return node;
    }    
    //先序遍历
    public static void preOrder(Tnode node,StringBuilder sb){
        if(node!=null){
            sb.append(node.val+"!");
            preOrder(node.l,sb);
            preOrder(node.r,sb);
        }else{sb.append("#!");}        
    }
    //层序遍历
    public static void cxOrder(Queue<Tnode> nodes,StringBuilder sb){
        if(!nodes.isEmpty()){
            Tnode temp=nodes.poll();
            if(temp!=null){
                sb.append(temp.val+"!");
                nodes.offer(temp.l);
                nodes.offer(temp.r);
            }else{
                sb.append("#!");
            }
            cxOrder(nodes,sb);
        }
    }    
}
class Tnode{
    public int val;
    public Tnode l;
    public Tnode r;
    public Tnode(){};
    public Tnode(int val){this.val=val;}
}

全部评论

相关推荐

03-27 20:14
前端工程师
投票
Spring启动:我在一嗨呆过,这么说吧 神仙单位,除了工资不怎么好 剩下的基本上天花板了,上班下班跟公务员似的,一天工作7个点,提供宿舍,宿舍离公司1km, 项目不着急,一般来说1天的活,你要个4天没人管你,我一天上班4个点在微信上跟别人聊天😂 去那边老自在了 但是也有可能是 我们组比较好
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务