leetcode练习
117. 填充每个节点的下一个右侧节点指针 II
题目
这道题,比较简单的思想就是层次遍历,每次遍历一层的节点,每层的节点数由n记录,不能直接i < queue.size()因为队列是在不停变化的。
public Node connect(Node root) {
if (root == null) return null;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()){
Node last = null;
int n = queue.size();
for (int i = 0; i < n; i++){
Node f = queue.poll();;
if (f.left != null){
queue.add(f.left);
}
if (f.right != null){
queue.add(f.right);
}
if (i > 0){
last.next = f;
}
last = f;
}
}
return root;
}
还可以根据上一层已经建立好连接的思想,加入全局变量,nextStart记录下一层开始的父节点,last记录当前层最后一位,关键是for循环遍历当前层所有节点
Node last = null, nextStart = null;
public Node connect1(Node root) {
if (root == null) {
return null;
}
Node start = root;
while (start != null) {
last = null;
nextStart = null;
for (Node p = start; p != null; p = p.next) {
if (p.left != null) {
handle(p.left);
}
if (p.right != null) {
handle(p.right);
}
}
start = nextStart;
}
return root;
}
public void handle(Node p) {
if (last != null) {
last.next = p;
}
if (nextStart == null) {
nextStart = p;
}
last = p;
}
572. 另一棵树的子树
题目
该题还有kmp算法和哈希树两种解法,需要继续完善。
public boolean isSubtree(Node s, Node t) {
if (t == null) return true; // t 为 null 一定都是 true
if (s == null) return false; // 这里 t 一定不为 null, 只要 s 为 null,肯定是 false
return isSubtree(s.left, t) || isSubtree(s.right, t) || isSameTree(s,t); // 判断是左子树、右子树还是当前树和目标树相同
}
//前序遍历查找节点
public Node findRoot(Node root, Node subRoot){
if (root == null) return null;
if (root.val == subRoot.val) return root;
Node re = null;
re = findRoot(root.left, subRoot);
if (re != null) return re;
re = findRoot(root.right, subRoot);
return re;
}
//判断两个树是否相同
public boolean isSameTree(Node s, Node t){
if (s == null && t == null) return true;
if (s == null || t == null) return false;
if (s.val != t.val) return false;
return isSameTree(s.left, t.left) && isSameTree(s.right, t.right);
}