题解 | 序列化二叉树

序列化二叉树

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

import java.util.*;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
public class Solution {

    //获取树的高度
    static public int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(height(root.left), height(root.right)) + 1;
    }
    static TreeNode Deserialize(String str) {
        if (str.isEmpty()) {
            return null;
        }
        List<TreeNode> list = new ArrayList<>();
        String[] split = str.split(",");
        if (split.length < 2) {
            return null;
        }
        for (int i = 0; i < split.length; i++) {
            if (!split[i].equals("-1")) {
                list.add(new TreeNode(Integer.parseInt(split[i])));
            } else {
                list.add(null);
            }
        }
        for (int j = 0; j < list.size() / 2; j++) {
            TreeNode node = list.get(j);
            if (node != null) {
                TreeNode treeNode = list.get(j * 2);
                if (treeNode != null) {
                    node.left = list.get(j * 2);
                }
                TreeNode treeNode1 = list.get(j * 2 + 1);
                if (treeNode1 != null) {
                    node.right = list.get(j * 2 + 1);
                }
            }
        }
        return list.get(1);
    }
    // 这里采用任何一种遍历都行
    static private void preorder(TreeNode root, int index, int[] arr) {
        if (root == null) {
            return;
        }
        arr[index] = root.val;
        preorder(root.left, index * 2, arr);
        preorder(root.right, index * 2 + 1, arr);
    }

    static String Serialize(TreeNode root) {
        int height = height(root);
        int[] arr = new int[(int) Math.pow(2, height)];
        Arrays.fill(arr, -1);
        preorder(root, 1, arr);
        StringBuffer sb = new StringBuffer();
        for (int j : arr) {
            sb.append(j).append(",");
        }
        return sb.substring(0, sb.length() - 1);
    }


}

全部评论

相关推荐

点赞 评论 收藏
分享
01-23 19:11
已编辑
门头沟学院 前端工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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