najimCseJu

Untitled

Sep 3rd, 2019
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. //https://leetcode.com/problems/serialize-and-deserialize-bst/
  2. /**
  3.  * Definition for a binary tree node.
  4.  * public class TreeNode {
  5.  *     int val;
  6.  *     TreeNode left;
  7.  *     TreeNode right;
  8.  *     TreeNode(int x) { val = x; }
  9.  * }
  10.  */
  11. public class Codec {
  12.  
  13.     // Encodes a tree to a single string.
  14.     public String serialize(TreeNode root) {
  15.         if(root==null)return "#";
  16.         return Integer.toString(root.val) + "," + serialize(root.left) + "," + serialize(root.right);
  17.     }
  18.     class Data{
  19.         TreeNode node;
  20.         int f;
  21.         Data(TreeNode n){
  22.             node = n;
  23.             f = 0;
  24.         }
  25.     }
  26.     TreeNode decode(String[] v) {
  27.         Stack<Data> stk = new Stack();
  28.         for (int i = 0; i < v.length; i++) {
  29.             while (!stk.isEmpty() && stk.peek().f == 2) {
  30.                 stk.pop();
  31.             }
  32.             TreeNode node = v[i].equals("#") ? null : new TreeNode(Integer.parseInt(v[i]));
  33.             if (node == null && stk.isEmpty()) return null;
  34.             if (!stk.isEmpty()) {
  35.                 Data top = stk.peek();
  36.                 if (top.f == 0) {
  37.                     top.node.left = node;
  38.                 } else {
  39.                     top.node.right = node;
  40.                 }
  41.                 top.f++;
  42.             }
  43.             if (node != null) stk.push(new Data(node));
  44.         }
  45.         while (stk.size() >= 2) stk.pop();
  46.         return stk.pop().node;
  47.     }
  48.     // Decodes your encoded data to tree.
  49.     public TreeNode deserialize(String data) {
  50.         System.out.println(data);
  51.         return decode(data.split(","));
  52.     }
  53. }
  54.  
  55. // Your Codec object will be instantiated and called as such:
  56. // Codec codec = new Codec();
  57. // codec.deserialize(codec.serialize(root));
Advertisement
Add Comment
Please, Sign In to add comment