【二叉树】572. 另一棵树的子树

572. 另一棵树的子树

解题思路

  • 遍历二叉树的思路
  • 针对每一个节点判断该节点的子树和subtree是不是相等
  • 需要编写判断两个子树是否相等的函数



/**
 * 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);

    }
}

猜你喜欢

转载自blog.csdn.net/qq_44653420/article/details/132419547