DEV Community

Cover image for Same Tree
FakeStandard
FakeStandard

Posted on • Edited on

2

Same Tree

#100.Same Tree

Problem statement

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

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

Example 1

Input: p = [1,2,3], q = [1,2,3]
Output: true
Enter fullscreen mode Exit fullscreen mode

Example 2

Input: p = [1,2], q = [1,null,2]
Output: false
Enter fullscreen mode Exit fullscreen mode

Explanation

給定兩個二元樹的樹根 pq ,檢查兩個二元樹是否相同,相同的定義為結構相同、節點也具有相同的值,最終返回 truefalse

Solution

有關二元樹的題目,解法通常離不開遞迴,這題要比較兩個二元樹結構是否完全相同,用遞迴可寫出優雅的解法,一開始先判斷二元樹是否為 null,若其中一個是 null,返回兩者是否相等的判斷結果,若兩個節點都不是 null,則比較兩者節點值是否相同,若不同則在最底部返回 false,若節點值相同則繼續走訪左子樹和右子樹,呼叫自己 IsSameTree 並傳入要比較的對應節點,直到判斷完成

public bool IsSameTree(TreeNode p, TreeNode q)
{
    if (p == null || q == null) return p == q;

    if (p.val == q.val)
        return IsSameTree(p.left, q.left) && IsSameTree(p.right, q.right);

    return false;
}
Enter fullscreen mode Exit fullscreen mode

Reference

LeetCode Solution

GitHub Repository


Thanks for reading the article 🌷 🌻 🌼

If you like it, please don't hesitate to click heart button ❤️
or click like on my Leetcode solution
or follow my GitHub ⭐ I'd appreciate it.


Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay