劍指offer-序列化二叉樹

請實現兩個函數,分別用來序列化和反序列化二叉樹。app

前序遍歷函數

public class Solution {
    int index =0;
    String Serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        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[] s = str.split(",");
        index =-1;
        return DeserHelp(s);
    }
    TreeNode DeserHelp(String[] str){
        TreeNode root = null;
        index++;
        if(!"#".equals(str[index])){
            root = new TreeNode(Integer.valueOf(str[index]));
            root.left = DeserHelp(str);
            root.right = DeserHelp(str);
        }
        return root;
    }
}

還可用層次遍歷ui

相關文章
相關標籤/搜索