题目链接
给你两棵二叉树 root 和 subRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在,返回 true ;否则,返回 false 。
二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。tree 也可以看做它自身的一棵子树。
示例 1:
输入:root = [3,4,5,1,2], subRoot = [4,1,2]
输出:true
示例 2:
输入:root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
输出:false
提示:
- root 树上的节点数量范围是 [1, 2000]
- subRoot 树上的节点数量范围是 [1, 1000]
- -10^4 <= root.val <= 10^4
- -10^4 <= subRoot.val <= 10^4
解答
迭代写法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
// 遍历root,找到节点值为subRoot根节点值的节点
Queue nodeQueue = new LinkedList<>();
nodeQueue.add(root);
TreeNode node;
while (!nodeQueue.isEmpty()) {
node = nodeQueue.poll();
if (node.val == subRoot.val) {
// 从node节点开始寻找是否有与subRoot相同的子树结构
Queue rootNodes = new LinkedList<>();
Queue subNodes = new LinkedList<>();
rootNodes.add(node);
subNodes.add(subRoot);
TreeNode rootNode, subNode;
boolean isDiff = false;
while (!rootNodes.isEmpty() && !subNodes.isEmpty()) {
rootNode = rootNodes.poll();
subNode = subNodes.poll();
// 检测两棵树当前节点值是否相同
if (rootNode.val != subNode.val) { isDiff = true; break; }
// 检测两棵树当前节点是否同时存在或不存在左子节点
if (rootNode.left == null) {
if (subNode.left != null) { isDiff = true; break; }
} else
if (subNode.left == null) { isDiff = true; break; }
else {
rootNodes.add(rootNode.left);
subNodes.add(subNode.left);
}
// 检测两棵树当前节点是否同时存在或不存在右子节点
if (rootNode.right == null) {
if (subNode.right != null) { isDiff = true; break; }
} else
if (subNode.right == null) { isDiff = true; break; }
else {
rootNodes.add(rootNode.right);
subNodes.add(subNode.right);
}
}
if (!isDiff) return true;
}
if (node.left != null) nodeQueue.add(node.left);
if (node.right != null) nodeQueue.add(node.right);
}
return false;
}
}
双重递归写法
// 递归调用解法
public boolean isSubTree(TreeNode root, TreeNode subRoot) {
if (root == null && subRoot == null) return true;
if (root == null && subRoot != null || root != null && subRoot == null) return false;
return isSameTrees(root, subRoot) || isSameTrees(root.left, subRoot) || isSameTrees(root.right, subRoot);
}
public boolean isSameTrees(TreeNode rootNode, TreeNode subNode) {
if (rootNode == null && subNode == null) return true;
if (rootNode == null && subNode != null || rootNode != null && subNode == null) return false;
return isSameTrees(rootNode.left, subNode.left) && isSameTrees(rootNode.right, subNode.right);
}