Easy Java Solution


  • 0
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isSubtree(TreeNode s, TreeNode t) {
            if(s == null && t == null) return true;
            else if(s == null && t != null) return false;
            else if(t == null) return true;
            
            if(checkSame(s,t)) return true;
            else {
                return isSubtree(s.left,t) || isSubtree(s.right, t);
            }
            
        }
        
        private boolean checkSame(TreeNode first, TreeNode second) {
            if(first == null && second != null) return false;
            else if(first != null && second == null) return false;
            else if(first == null && second == null) return true;
            else {
                return first.val == second.val && checkSame(first.left, second.left) && checkSame(first.right, second.right);
            }
        }
        
    }
    

Log in to reply
 

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