JZ61 序列化二叉树

序列化二叉树

https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84?tpId=13&&tqId=11214&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

java 也有split操作
str.substring(0, str.length() - 1).split(",");

import java.util.*;

//层序遍历
class Solution {
    String Serialize(TreeNode root) {
        //根节点为空 单独考虑
        if(root == null) return "";

        Queue<TreeNode> queue2 = new LinkedList<TreeNode>();
        queue2.offer(root);
        StringBuilder res = new StringBuilder();

        while(!queue2.isEmpty()){
            TreeNode temp = queue2.poll();
            if(temp == null ) res.append("#").append(",");
            //这bug不容易查出来 原来后面没加括号
            //一定是对流程非常熟悉
            else {
                res.append(String.valueOf(temp.val)).append(",");
                queue2.offer(temp.left);
                queue2.offer(temp.right);
            }
        }
        return res.toString();
    }

    TreeNode Deserialize(String str) {
        //根节点为空 单独考虑
        if(str.equals("")) return null;
        //分割
        String[] vals = str.substring(0, str.length() - 1).split(",");
        // 根节点加入队列
        TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        //根节点的有孩子在 位置 i上
        int i = 1;
        while(!queue.isEmpty() && i<vals.length) {

            TreeNode node = queue.poll();
            // 处理右孩子
            if(!vals[i].equals("#")) {
                node.left = new TreeNode(Integer.parseInt(vals[i]));
                queue.add(node.left);
            }
            i++;
            // 处理左孩子
            if(!vals[i].equals("#")) {
                node.right = new TreeNode(Integer.parseInt(vals[i]));
                queue.add(node.right);
            }
            i++;
        }
        return root;
    }
}
全部评论

相关推荐

找个工作&nbsp;学历是要卡的&nbsp;要求是高的&nbsp;技能不足是真的&nbsp;实习经验是0的&nbsp;简历无处可写是事实的&nbsp;钱不好赚是真的&nbsp;想躺平又不敢躺&nbsp;也不甘心躺&nbsp;怕自己的灵感和才华被掩埋甚至从未被自己发现&nbsp;又质疑自己是否真正有才华
码农索隆:你现在啊,你心里都明白咋回事,但是你没办法改变现状,一想到未来,你又没有信心狠下心来在当下努力。 得走出这种状态,不能一直困在那里面,哪不行就去提升哪,你一动不动那指定改变不了未来,动起来,积少成多才能越来越好
点赞 评论 收藏
分享
星辰再现:裁员给校招生腾地方
点赞 评论 收藏
分享
白火同学:大二有这水平很牛了,可以适当对关键信息加粗一点,比如关键技术、性能指标之类的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务