序列化二叉树

序列化二叉树_第1张图片

解题思路一:

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 {

    int index = -1;
    String Serialize(TreeNode root) {

        StringBuffer result = new StringBuffer();

        if(root == null){
            return result.append("#,").toString();
        }

        result.append(root.val + ",");
        result.append(Serialize(root.left));
        result.append(Serialize(root.right));

        return result.toString();
    }
    TreeNode Deserialize(String str) {

        index++;

        if(index >= str.length()){
            return null;
        }

        TreeNode node = null;
        String[] strArr = str.split(",");
        String val = strArr[index];

        if(!"#".equals(val)){
            node = new TreeNode(Integer.parseInt(val));
            node.left = Deserialize(str);
            node.right = Deserialize(str);
        }

        return node;
    }
}

你可能感兴趣的:(算法,算法,leetcode,职场和发展)