Concise and Clear Java Solution


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

Log in to reply
 

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