【二分木】572. 別の木の部分木

572. 別の木のサブツリー

問題解決のアイデア

  • 二分木を走査するという考え方
  • 各ノードについて、サブツリーとノードのサブツリーが等しいかどうかを判断します。
  • 2 つのサブツリーが等しいかどうかを判断する関数を記述する必要があります



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