Java Solution using matching roots list.

  • 0
    public boolean isSubtree(TreeNode s, TreeNode t) {
        List<TreeNode> matches = new ArrayList<>();
        findMatchingNode( s,  t, matches);
        for(TreeNode match: matches)
            if(isSameTree(match, t)) return true;
        return false;
    public boolean isSameTree(TreeNode s, TreeNode t)
        if(s==null && t==null) return true;
        if(s==null && t!=null) return false;
        if(s!=null && t==null) return false;
        return (s.val==t.val) && isSameTree(s.left,t.left) && isSameTree(s.right,t.right);
    public void findMatchingNode(TreeNode s, TreeNode t, List<TreeNode> matches)
        if(s==null) return;
        findMatchingNode(s.left,t, matches);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.