剑指 Offer 37. 序列化二叉树 + 二叉树的层次遍历
剑指 Offer 37. 序列化二叉树
Offer_37
题目描述
题目解析
- 本题主要考察的就是二叉树的层次遍历。
- 层次遍历时可以根据二叉树的特点将空结点也进栈。
- 反序列化时同样可以根据层次遍历的思路,每次生成当前结点的左右子树指针结点。
java代码
package com.walegarrett.offer;
/**
* @Author WaleGarrett
* @Date 2021/2/4 23:01
*/
import java.util.LinkedList;
import java.util.Queue;
/**
* 题目描述:请实现两个函数,分别用来序列化和反序列化二叉树。
* 你可以将以下二叉树:
* 1
* / \
* 2 3
* / \
* 4 5
* 序列化为 "[1,2,3,null,null,4,5]"
*/
public class Offer_37 {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root == null)
return "[]";
Queue<TreeNode> que = new LinkedList<>();
que.add(root);
String s = "[";
while(!que.isEmpty()){
TreeNode now = que.poll();
if(now != null){
que.add(now.left);
que.add(now.right);
s = s + String.valueOf(now.val) + ",";
}else s += "null,";
}
s = s.substring(0, s.length()-1);
s+="]";
return s;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data.length() <= 2)
return null;
data = data.substring(1, data.length() - 1);
String []s = data.split(",");
int len = s.length;
TreeNode head = new TreeNode(Integer.parseInt(s[0]));
Queue<TreeNode> que = new LinkedList<>();
que.add(head);
int index = 1;
while(!que.isEmpty()){
TreeNode now = que.poll();
if(!s[index].equals("null")){
now.left = new TreeNode(Integer.parseInt(s[index]));
que.add(now.left);
}
index++;
if(!s[index].equals("null")){
now.right = new TreeNode(Integer.parseInt(s[index]));
que.add(now.right);
}
index++;
}
return head;
}
}
Either Excellent or Rusty