剑指offer-二叉树的序列化和反序列化(困惑)-Java

今天在牛客上做这个题,发现一个很奇怪的事,以下第一个代码能AC,第二个却不能,但其实我个人觉得第二个更好,也不知道牛客的测试用例是怎么写的。

题目描述

请实现两个函数,分别用来序列化和反序列化二叉树


代码一:

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
public class Solution {
     public int index = -1;
    String Serialize(TreeNode root) {
        StringBuffer sb = new StringBuffer();
        if(root == null){
            sb.append("#,");
            return sb.toString();
        }
        sb.append(root.val + ",");
        sb.append(Serialize(root.left));
        sb.append(Serialize(root.right));
        return sb.toString();
  }
    TreeNode Deserialize(String str) {
        String[] strr = str.split(",");
        int len = strr.length;
        index++;
        if(index >= len){
            return null;
        }
        TreeNode node = null;
        if(!strr[index].equals("#")){
            node = new TreeNode(Integer.valueOf(strr[index]));
            node.left = Deserialize(str);
            node.right = Deserialize(str);
        }
         
        return node;
  }
}

代码二:

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
import java.util.*;
public class Solution {
    String Serialize(TreeNode root) {
        if(root == null)
			return "#,";
		StringBuffer st = new StringBuffer();
		st.append(root.val+",");
		st.append(Serialize(root.left));
		st.append(Serialize(root.right));
		return st.toString();
  }
    TreeNode Deserialize(String str) {
       if(str == null || str.length() == 0)
			return null;
		Queue qu = new LinkedList<>();
		String[] arr = str.split(",");
		int len = arr.length;
		for(int i = 0; i < len; i++){
			qu.add(arr[i]);
		}
		return buildTree(qu);
  }
    TreeNode buildTree(Queue qu){
		if(qu.size() == 0)
			return null;
		String cur = qu.poll();
		if(cur == "#")
			return null;
		TreeNode root = new TreeNode(Integer.valueOf(cur));
		root.left = buildTree(qu);
		root.right = buildTree(qu);
		return root;
	}
}


你可能感兴趣的:(Java,Leetcode,找工作相关)