Offer to prove safety substructure tree

Title Description

Two binary inputs A, B, B is judged not substructure A's.

Thinking

If the root node is the same recursive call isSubtreeWithRoot (), if the root node is not the same, then the left subtree is determined and root1 roo2 are the same, then judge whether the right subtree and root2 same;
attention node empty condition, isSubStructure () in , as long as the tree is empty return false; isSubtreeWithRoot (), the first determination root2, if root2 is empty, then the second tree traversal over, i.e., the match succeeds.

Reference Code

class Solution {
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if (A == null || B == null) {
            return false;
        }

        return (isSubtreeWithRoot(A, B)  || isSubStructure(A.left, B) || isSubStructure(A.right, B));
    }

    public boolean isSubtreeWithRoot(TreeNode root1, TreeNode root2) {
            if (root2 == null) return true;
            if (root1 == null) return false;
            if (root1.val != root2.val) return false;
            return isSubtreeWithRoot(root1.left, root2.left) && isSubtreeWithRoot(root1.right, root2.right); 
    }
}
Released seven original articles · won praise 0 · Views 1349

Guess you like

Origin blog.csdn.net/Incanus_/article/details/105252840