Super easily readable fast O(n) Java solution


  • 0
    C
    public class Solution {
        public boolean isSubtree(TreeNode s, TreeNode t) {
            if (s == null && t == null) return true;
            if (s != null && t == null) return true;
            if (s == null && t != null) return false;
            
            return s.val == t.val && isSameTree(s,t) || 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.