572. A Subtree of Another Tree
problem solving ideas
- The idea of traversing a binary tree
- For each node, determine whether the subtree and subtree of the node are equal
- Need to write a function to judge whether two subtrees are equal
/**
* 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 isSame(TreeNode root,TreeNode root1){
// 二叉树的遍历问题 针对当前节点 写出所有递归出口
if(root == null && root1 == null){
return true;
}
if(root == null || root1 == null){
return false;
}
if(root.val != root1.val){
return false;
}
return isSame(root.left,root1.left) && isSame(root.right,root1.right);
}
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
// 二叉树的遍历问题 针对二叉树每一个点继续遍历 模板题
// 对于遍历到的每一个节点 也就是先写出递归出口
if(root == null){
return subRoot == null;
}
if(isSame(root,subRoot)){
return true;
}
// 从左右子树开始继续寻找是否有相同的子树
return isSubtree(root.left,subRoot) || isSubtree(root.right,subRoot);
}
}