Recursive Java Solution Easy to Understand


  • 0
    A
    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 (helper(s,t)) {
                return true;
            }
            return isSubtree(s.left, t) || isSubtree(s.right, t);
        }
        
        public boolean helper(TreeNode s, TreeNode t) {
            if(s == null && t == null) {
                return true;
            } else if (s ==  null || t == null) {
                return false;
            } else if(s.val == t.val) {
                return helper(s.left, t.left) && helper(s.right, t.right);
            }
            return false;
        }
    }

Log in to reply
 

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