题目:树的子结构
方法一:广度优先遍历
public class Solution {
public boolean HasSubtree(TreeNode root1, TreeNode root2) {
if (root1 == null || root2 == null) {
return false;
}
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root1);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (startsWith(node, root2)) {
return true;
}
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
return false;
}
private boolean startsWith(TreeNode root1, TreeNode root2) {
if (root1 == null || root1.val != root2.val) {
return false;
}
if (root2.left != null && !startsWith(root1.left, root2.left)) {
return false;
}
if (root2.right != null && !startsWith(root1.right, root2.right)) {
return false;
}
return true;
}
}
方法二:深度优先遍历 (非递归)
public class Solution {
public boolean HasSubtree(TreeNode root1, TreeNode root2) {
if (root1 == null || root2 == null) {
return false;
}
Deque<TreeNode> stack = new ArrayDeque<>();
while (root1 != null) {
if (startsWith(root1, root2)) {
return true;
}
if (root1.right != null) {
stack.push(root1.right);
}
root1 = root1.left;
if (root1 == null) {
root1 = stack.poll();
}
}
return false;
}
private boolean startsWith(TreeNode root1, TreeNode root2) {
if (root1 == null || root1.val != root2.val) {
return false;
}
if (root2.left != null && !startsWith(root1.left, root2.left)) {
return false;
}
if (root2.right != null && !startsWith(root1.right, root2.right)) {
return false;
}
return true;
}
}
方法三:深度优先遍历 (递归)
public class Solution {
public boolean HasSubtree(TreeNode root1, TreeNode root2) {
if (root1 == null || root2 == null) {
return false;
}
return startsWith(root1, root2) || HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2);
}
private boolean startsWith(TreeNode root1, TreeNode root2) {
if (root1 == null || root1.val != root2.val) {
return false;
}
if (root2.left != null && !startsWith(root1.left, root2.left)) {
return false;
}
if (root2.right != null && !startsWith(root1.right, root2.right)) {
return false;
}
return true;
}
}