题解 | #序列化二叉树#

序列化二叉树

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

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

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

    }

}
*/
public class Solution {
    String Serialize(TreeNode root) {
        StringBuilder builder = new StringBuilder();
        getString(root, builder);
        return builder.toString();
    }

    private void getString(TreeNode root, StringBuilder builder) {
        if (root == null) {
            builder.append(",");
        } else {
            builder.append(root.val).append(",");
            getString(root.left, builder);
            getString(root.right, builder);
        }
    }


    TreeNode Deserialize(String str) {
        String[] strArray = str.split( ",");
        int[] ptr = new int[] {0};
        return dfs(strArray, ptr);
    }

    private TreeNode dfs(String[] strArray, int[] ptr) {
        if (ptr[0] >= strArray.length || strArray[ptr[0]].length() == 0) {
            ptr[0]++;
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(strArray[ptr[0]++]));
        node.left = dfs(strArray, ptr);
        node.right = dfs(strArray, ptr);
        return node;
    }
}

全部评论

相关推荐

11-09 11:01
济南大学 Java
Java抽象带篮子:外卖项目真得美化一下,可以看看我的详细的外卖话术帖子
点赞 评论 收藏
分享
我见java多妩媚:大外包
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务