• leetcode 序列化二叉树


    https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof/

    就是层级遍历,搞一个queue,然后层级遍历,左右子树为空也要add到queue,因为要保留整颗树的结构,反解析的时候同理,遇到为null的,就不添加queue了

    import java.util.LinkedList;
    import java.util.Queue;
    
    public class Codec {
        public String serialize(TreeNode root) {
            if(root == null) {
                return "[]" ;
            }
    
            StringBuilder stringBuilder = new StringBuilder();
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            stringBuilder.append("[");
            while (!queue.isEmpty()){
                TreeNode node = queue.poll();
                if(node != null) {
                    stringBuilder.append(node.val);
                    stringBuilder.append(",");
                    queue.add(node.left);
                    queue.add(node.right);
                } else {
                    stringBuilder.append("null,");
                }
            }
    
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
            stringBuilder.append("]");
    
            return stringBuilder.toString();
        }
    
        public TreeNode deserialize(String data) {
            if(data.equals("[]")) {
                return null;
            }
    
            String nodeStr = data.substring(1, data.length()-1);
            String[] nodeVal = nodeStr.split(",");
            TreeNode root = new TreeNode(Integer.parseInt(nodeVal[0]));
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            int index = 1;
            while (!queue.isEmpty()){
                TreeNode node = queue.poll();
                if(!nodeVal[index].equals("null")){
                    node.left = new TreeNode(Integer.parseInt(nodeVal[index]));
                    queue.add(node.left);
                }
    
                index++;
    
                if(!nodeVal[index].equals("null")){
                    node.right = new TreeNode(Integer.parseInt(nodeVal[index]));
                    queue.add(node.right);
                }
    
                index++;
            }
    
            return root;
        }
    }
    

      

  • 相关阅读:
    crossvcl使用
    CSS垂直居中的方法
    IIS7 启用GZip压缩
    javascript arguments解释,实现可变长参数。
    DataTable转List<dynamic>
    Bootstrap表单
    Func<T>、Action<T> 的区别于说明
    jQuery.fn.extend() 与 jQuery.extend()
    javascript this关键字指向详解
    javascript call与apply关键字的作用
  • 原文地址:https://www.cnblogs.com/iamzhoug37/p/12952655.html
Copyright © 2020-2023  润新知