The sword refers to the offer 26. The substructure of the tree

The sword refers to the offer 26. The substructure of the tree

Title description

Insert picture description here

Problem-solving ideas

class Solution {
    
    
    //判断树 B 是否是树 A 其中某一部分的子结构
    public boolean isSubStructure(TreeNode A, TreeNode B) {
    
    
        // base case
        if (A == null || B == null) return false;
        //当A、B均不为null时,先序遍历
        return isSub(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B);
    }

    //从 A、B 节点开始同步遍历,判断树 B 是否是树 A 的子结构
    public boolean isSub(TreeNode A, TreeNode B) {
    
    
        //若 B 遍历完毕,说明是子结构
        if (B == null) return true;
        //若 B 还没遍历完但 A 已遍历完,或者 A 和 B 的值不相同,则返回false
        if (A == null || A.val != B.val) return false;
        //当前节点比较完之后还要继续判断左右子节点
        return isSub(A.left, B.left) && isSub(A.right, B.right);
    }
}

Guess you like

Origin blog.csdn.net/cys975900334/article/details/115048296