117.填充每个节点的下一个右侧节点指针 II
给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
题解:
本题就是让把二叉树中每行都串起来,最合适的就是使用BFS进行一行一行的遍历。
法一:队列
class Solution {
public Node connect(Node root) {
if(root == null)
return root;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
//每一层的数量
int levelCount = queue.size();
//前一个节点
Node pre = null;
for(int i=0; i < levelCount; i++ ){
//出队
Node node = queue.poll();
//如果pre为空就表示node节点是这一行的第一个
//
if(pre != null){
pre.next = node;
}
//然后再让当前节点成为前一个节点
pre = node;
//左右子节点如果不为空就入队
if(node.left != null)
queue.add(node.left);
if(node.right != null)
queue.add(node.right);
}
}
return root;
}
}
法二:链表
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
if(root == null)
return root;
//cur把它看作每一层的链表
Node cur = root;
while(cur != null){
//遍历当前层时,为了方便操作在下一层前面添加一个哑节点(注意这里是访问当前层的节点,然后把下一层的节点串起来)
Node dummy = new Node(0);
//pre表示访问下一层节点的前一个节点
Node pre = dummy;
//然后开始遍历当前层的链表
while(cur != null){
if(cur.left != null){
//如果当前节点的左子节点不为空,就让pre节点的next指向它,也就是把它串起来
pre.next = cur.left;
//然后再更新pre
pre = pre.next;
}
//右子树同理
if(cur.right !=null){
pre.next = cur.right;
pre = pre.next;
}
//继续访问这一行的下一个节点
cur = cur.next;
}
//把下一层串联成一个链表之后,让他赋值给cur,后续继续循环,直到cur为空为止
cur = dummy.next;
}
return root;
}
}
572.另一棵子树
给你两棵二叉树 root 和 subRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在,返回 true ;否则,返回 false 。
二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。tree 也可以看做它自身的一棵子树。
题解:
判断两个数是否相等(与关系):
1.当前两个树的根节点的值相等
2.s的左子树和t的左子树相等
3.s的右子树和t的右子树相等
判断t是否为s的子树(或关系):
1.当前两棵树相等
2.t是s的左子树
3.t是s的右子树
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSubtree(self, s, t):
"""
:type root: TreeNode
:type subRoot: TreeNode
:rtype: bool
"""
#首先考虑特殊情况,都为空树和其中一颗为空树的情况
if not s and not t: #若s和t都为空树,两树相等
return True
if not s or not t: #若s和t有一棵为空树,则无法包含子树
return False
return self.isSameTree(s,t) or self.isSubtree(s.left,t) or self.isSubtree(s.right,t) #两树相等或s有和t相同的左子树或右子树
def isSameTree(self,s,t): #判断两树是否相等
if not s and not t:
return True
if not s or not t:
return False
return s.val == t.val and self.isSameTree(s.left,t.left) and self.isSameTree(s.right,t.right)