Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 100. Same Tree

Rain Hu

100. Same Tree


一、題目

Given the roots of two binary tree p and q, write a function to check if they are the same or not.
Two binary tree are considered the same if they are structurally iedntical, and the nodes have the same value.

Example 1:
ex1

Example 2:
ex2

Example 3: ex3

Constraints:


二、分析

三、解題

1. Recursion

bool 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 false;
    return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 1519. Number of Nodes in the Sub-Tree With the Same Level
Next
[LeetCode] 149. Max Points on a Line