Skip to content

Latest commit

 

History

History
37 lines (29 loc) · 719 Bytes

Same Tree.md

File metadata and controls

37 lines (29 loc) · 719 Bytes

Provided Code

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
}

Solution

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (p == null || q == null) {
            return false;
        }
        return p.val == q.val
            && isSameTree(p.left, q.left)
            && isSameTree(p.right, q.right);
    }
}

Time/Space Complexity

Let m be number of TreeNodes in p. Let n be number of TreeNodes in q.

  • Time Complexity: O(min(m + n))
  • Space Complexity: O(min(m + n))

Links