Java recursive search solution


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

Log in to reply
 

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