Recursive Java solution


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

Log in to reply
 

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