Prove safety offer: sub-tree (recursive)

topic:

Two binary inputs A, B, B is judged not substructure A's. (Ps: we agreed empty tree is not a tree any substructure)

answer:

Recursively, as follows:

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        if(root1==null||root2==null){
            return false;
        }
        return subTree(root1,root2)||subTree(root1.left,root2)||subTree(root1.right,root2);
        
    }
    public boolean subTree(TreeNode root1,TreeNode root2){
        if(root2==null){
            return true;
        }
        if(root1==null){
            return false;
        }
        if(root1.val==root2.val){
            return (subTree(root1.left,root2.left)&&subTree(root1.right,root2.right));
        }
        return false;
    }
}

 

Published 92 original articles · won praise 2 · Views 8411

Guess you like

Origin blog.csdn.net/wyplj2015/article/details/104866917