13 Lines Java Solution, Recursion


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

Log in to reply
 

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