• 剑指 Offer 37. 序列化二叉树


    // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            if(root == null) return "[]";
            Deque<TreeNode> deque = new LinkedList<>();
            deque.addLast(root);
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            while (!deque.isEmpty()){
                TreeNode node = deque.pollFirst();
                if(node!=null) {
                    sb.append(node.val);
                    sb.append(",");
                    deque.addLast(node.left);
                    deque.addLast(node.right);
                }else{
                    sb.append("null,");
                }
            }
            sb.deleteCharAt(sb.length()-1);  //删除结尾的逗号
            //将结尾的null删除
            while (sb.lastIndexOf("null")==sb.length()-4){
                sb.delete(sb.length()-5,sb.length());
            }
            sb.append("]");
            return sb.toString();
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if(data.equals("[]")) return null;
            data = data.substring(1,data.length()-1);
            String[] datas = data.split(",");
            ArrayList<TreeNode> list = new ArrayList<>();
            for (String s : datas) {  //将字符串转换为整数
                if (s.equals("null")) {
                    list.add(null);
                } else {
                    int x = Integer.parseInt(s);
                    list.add(new TreeNode(x));
                }
            }
            int len = list.size();
            TreeNode head = list.get(0);
            if(len == 1) return head;
            int i = 0,j = 1;
            while (j<len){
                if(list.get(i) == null) {
                    i++;
                    continue;
                }
                list.get(i).left = list.get(j);
                if(j+1<len){
                    list.get(i).right = list.get(j+1);
                }
                j+=2;
                i++;
            }
            return head;
        }

    这道题感觉算不上是难题

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    matlab中的匹配函数
    查看matlab中的小波基
    图像处理中的彩色图像处理
    OSEK Event mechanism
    OSEK OS Resource management
    ISO17356标准简介[转]
    OSEK OS标准简介(转)
    IQmath的使用方法
    HIVERT高压变频主电路构造原理
    MPPT算法
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/13533430.html
Copyright © 2020-2023  润新知