2015年8月9日星期日

[吐槽][口袋宝石] Serialize/Deserialize a Binary Tree

import java.util.ArrayList;
import java.util.List;


public class SerializeSolution {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(0);
        root.left = new TreeNode(1);
        root.right = new TreeNode(2);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(4);
        root.right.left = new TreeNode(5);
        root.right.right = new TreeNode(6);
        
        System.out.println(serialize(root));
        System.out.println(deserialize("0 1 3 # # 4 # # 2 5 # # 6 # #"));
    }
    
    public static String serialize(TreeNode root) {
        if (root == null) {
            return "#";
        }
        return Integer.toString(root.val) + " " + 
                serialize(root.left) + " " + serialize(root.right);
    }
    
    public static TreeNode deserialize(String s) {
        if (s == null || s.length() == 0) {
            return null;
        }
        List<String> nodes = new ArrayList<String>();
        for (String tmp : s.split(" ")) {
            nodes.add(tmp);
        }
        return helper(nodes);    
    }
    
    public static TreeNode helper(List<String> nodes) {
        if (nodes.size() == 0) {
            return null;
        }
        
        if (nodes.get(0).equals("#")) {
            nodes.remove(0);
            return null;
        }
        
        int val = Integer.parseInt(nodes.get(0));
        nodes.remove(0);
        TreeNode root = new TreeNode(val);
        root.left = helper(nodes);
        root.right = helper(nodes);
        
        return root;
    }
}

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    
    public TreeNode(int val) {
        this.val = val;
    }

    @Override
    public String toString() {
        return "TreeNode [val=" + val + ", left=" + left + ", right=" + right
                + "]";
    }
}

没有评论:

发表评论