k神题解理解后写出
分析后可知输入序列是层序遍历
输入[1,3,5,null,null,4,6]
指 | 1 | 3 | 5 | null | null | 4 | 6 | null | null | null | null |
---|
索引 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
根据层序特点
n是当前节点的索引,m是0到n中null的个数
node.left = 2(n-m)+1 node.right=2(n-m)+2
public class Codec {
public String serialize(TreeNode root) {
if(root==null) return "[]" ;
StringBuilder res = new StringBuilder("[");
Queue<TreeNode> queue = new LinkedList<TreeNode>(){{add(root);}};
while(!queue.isEmpty()){
if(queue.peek()==null) {
queue.remove();
res.append("null,");
}
else{
TreeNode node = queue.remove();
res.append(node.val+",");
queue.add(node.left);
queue.add(node.right);
}
}
res.deleteCharAt(res.length()-1);
res.append("]");
return res.toString();
}
public TreeNode deserialize(String data) {
if(data.equals("[]")) return null;
String[] num = data.substring(1,data.length()-1).split(",");
TreeNode root = new TreeNode(Integer.parseInt(num[0]));
Queue<TreeNode> queue = new LinkedList<TreeNode>(){{add(root);}};
int i=1;
while(!queue.isEmpty()){
TreeNode node = queue.remove();
if(!num[i].equals("null")){
node.left = new TreeNode(Integer.parseInt(num[i]));
queue.add(node.left);
}
i++;
if(!num[i].equals("null")){
node.right = new TreeNode(Integer.parseInt(num[i]));
queue.add(node.right);
}
i++;
}
return root;
}
}
DFS加减枝
HashSet 基于 HashMap 来实现的,是一个不允许有重复元素的集合
class Solution {
List<String> res = new LinkedList<>();
char[] c ;
public String[] permutation(String s) {
c = s.toCharArray();
dfs(0);
return res.toArray(new String[res.size()]);
}
void dfs(int x){
if(x==c.length-1) {
res.add(String.valueOf(c));
return;
}
HashSet<Character> set = new HashSet<Character>();
for(int i=x;i<c.length;i++){
if(set.contains(c[i])) continue;
set.add(c[i]);
swap(i,x);
dfs(x+1);
swap(i,x);
}
}
void swap(int a,int b){
char tmp = c[a];
c[a] = c[b];
c[b] = tmp;
}
}
|