序列化二叉树

题目描述

请实现两个函数,分别用来序列化和反序列化二叉树

分析

先序遍历,递归。

代码:

public class Solution {
public int index = -1;
StringBuilder sb = new StringBuilder();
String Serialize(TreeNode root) {
if (root == null){
sb.append("#,");
return sb.toString();
}
sb.append(root.val + ",");
Serialize(root.left);
Serialize(root.right);
return sb.toString();
}
TreeNode Deserialize(String str) {
index++;
int len = str.length();
if(index > len)
return null;
String[] strr = str.split(",");
TreeNode node = null;
if(!strr[index].equals("#")){
node = new TreeNode(Integer.valueOf(strr[index]));
node.left = Deserialize(str);
node.right = Deserialize(str);
}
return node;
}
}

欢迎关注公众号: FullStackPlan 获取更多干货

Copyright © 2016 - 2017 LBD All Rights Reserved.

访客数 : | 访问量 :