Woodstock Blog

a tech blog for general algorithmic interview questions

[LeetCode 100] Same Tree

Question

link

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

Stats

Frequency 1
Difficulty 1
Adjusted Difficulty 1
Time to use --------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

This is an easy one

Code

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