二叉树的序列化

题目描述:

二叉树的序列化:
将二叉树转化为一个字符串,可以用前中后序任何一种遍历进行.
普通节点用val值表示,空节点用#表示,不同节点直接用_隔开

 

代码:

 1 //将二叉树转为字符串
 2     public static String serialBypre(Node root) {
 3         if (root == null) {
 4             return "#_";
 5         }
 6         String res = root.val + "_";
 7         res += serialBypre(root.left);
 8         res += serialBypre(root.right);
 9         return res;
10     }

 

反序列化:
把得到的字符串恢复为二叉树

代码:

 1 //将字符串分割回二叉树
 2     public static Node reconBypre(String str) {
 3         String[] values = str.split("_");
 4         Queue<String> q = new LinkedList<>();
 5         for (int i = 0; i < values.length; i++) {
 6             q.add(values[i]);
 7         }
 8         return reconPreorder(q);
 9     }
10     
11     public static Node reconPreorder(Queue<String> q) {
12         String value = q.poll();
13         if (value.equals("#")) {
14             return null;
15         }
16         int val = Integer.valueOf(value);
17         Node head = new Node(val);
18         head.left = reconPreorder(q);
19         head.right = reconPreorder(q);
20         return head;
21     }

 

posted @ 2022-04-15 20:38  jue1e0  阅读(61)  评论(0)    收藏  举报