Easy to understand Java solution


  • 0
    M
    public boolean isSubtree(TreeNode s, TreeNode t) {
            if (s == null && t == null) {
                return true;
            } else if (s == null ||  t == null) {
                return false;
            }
            
            return isSubtreeHelper(s, t) || isSubtree(s.left, t) || isSubtree(s.right, t);
        }
        
        private boolean isSubtreeHelper(TreeNode s, TreeNode t) {
            
            if (s == null && t == null) {
                return true;
            }
            
            if (s == null ||  t == null) {
                return false;
            }
            
            if (s.val == t.val && isSubtreeHelper(s.left, t.left) && isSubtreeHelper(s.right, t.right)) {
                return true;
            }
            
            return false;
        }
    

Log in to reply
 

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