剑指Offer第二十八天
搜索与回溯算法(困难)
序列化二叉树居然是困难?。。
题1:序列化二叉树
请实现两个函数,分别用来序列化和反序列化二叉树。
你需要设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
提示:输入输出格式与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
//二叉树的前向遍历进行序列化
if(root == null){
return "null,";
}
String res = root.val + ",";
res += serialize(root.left);
res += serialize(root.right);
return res;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
//根据前向遍历的方式进行反序列化
String[] s = data.split(",");
Queue<String> queue = new LinkedList<String>();
//将所有元素加到队列里面
for(int i = 0; i < s.length; i++){
queue.offer(s[i]);
}
return helper(queue);
}
public TreeNode helper(Queue<String> queue){
//取出元素
String val = queue.poll();
if(val.equals("null")){
return null;
}
TreeNode root = new TreeNode(Integer.valueOf(val));
root.left = helper(queue);
root.right = helper(queue);
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
题2:队列的最大值
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
class Solution {
public String[] permutation(String s) {
//Set存储不重复的元素
Set<String> list = new HashSet<>();
char[] ch = s.toCharArray();
StringBuilder sb = new StringBuilder();
//用于记录该元素是否访问过
boolean[] visited = new boolean[ch.length];
dfs(ch, "", visited, list);
return list.toArray(new String[0]);
}
public void dfs(char[] ch, String s, boolean[] visited, Set<String> list){
if(s.length() == ch.length){
list.add(s);
return ;
}
for(int i = 0; i < ch.length; i++){
if(visited[i]){
continue;
}else{
visited[i] = true;
dfs(ch, s+String.valueOf(ch[i]), visited, list);
visited[i] = false;
}
}
}
}