题解 | #序列化二叉树# | JAVA | DFS

序列化二叉树

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

采用DFS遍历
用先序遍历很简单 , 因为先序是 中 , 左, 右 , 所有用index下标控制就行了。

public class Solution {
    String Serialize(TreeNode root) {
        if (root == null) {
            return "#";
        }
        //用先序遍历很简单 , 因为先序是  中 , 左,  右 , 所有用index下标控制就行了。 
        return root.val + "," + Serialize(root.left) + "," + Serialize(root.right);
    }


    TreeNode Deserialize(String str) {
        String[] arr = str.split(",");
        return buildTree(arr);
    }

    public int index = 0;

    private TreeNode buildTree(String[] arr) {
        String curr = arr[index];
        index++;
        if (curr.equals("#")) {
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(curr));
        root.left = buildTree(arr);
        root.right = buildTree(arr);
        return root;
    }
}
全部评论

相关推荐

见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 11:20
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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