题解 | #序列化二叉树#

序列化二叉树

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

方法一:广度优先遍历yyds

只要找到最大深度deep,判断当前深度level小于deep时,若子节点为空就插入“#”,就可以解决空值插入“#”的问题

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.*;
public class Solution {
    String Serialize(TreeNode root) {
        LinkedList<TreeNode> list = new LinkedList<>();
        if(root==null) return "";
        list.add(root);
        int deep = deep(root);
        int level = 1;
        String bts = root.val + ",";
        while(!list.isEmpty()){
            int curSize = list.size();
            while(curSize>0){
                TreeNode node = list.pop();
                if(node.left!=null){
                    list.add(node.left);
                    bts = bts + node.left.val+",";
                }else if(level<deep && node.left == null){
                    bts = bts +"#,";
                }
                if(node.right!=null){
                    list.add(node.right);
                     bts = bts + node.right.val+",";
                }else if(level<deep && node.right == null){
                    bts = bts +"#,";
                }
                curSize--;
            }
            level++;
        }
        bts = bts.substring(0,bts.length()-1);
        return bts;
    }
    TreeNode Deserialize(String str) {
        if(str.equals("")){return null;}
        String[] ss = str.split(",");
        int n = ss.length;
        TreeNode root = new TreeNode(Integer.parseInt(ss[0]));
        Deque<TreeNode> d = new ArrayDeque<>();
        d.addLast(root);
        for(int i=1;i<n-1;i+=2){
            TreeNode poll = d.pollFirst();
            String a = ss[i];
            String b = ss[i+1];
            if(!a.equals("#")){
                poll.left = new TreeNode(Integer.parseInt(ss[i]));
                d.addLast(poll.left);
            }
            if(!b.equals("#")){
                poll.right = new TreeNode(Integer.parseInt(ss[i+1]));
                d.addLast(poll.right);
            }
        }
        return root;
    }
    public int deep(TreeNode node){
        return node==null?0:Math.max(deep(node.left),deep(node.right))+1;
    }
}
全部评论

相关推荐

11-18 16:08
福州大学 Java
影流之主:干10年不被裁,我就能拿别人一年的钱了,日子有盼头了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务