--- title: 'LeetCode 100. Same Tree' disqus: hackmd --- # LeetCode 100. Same Tree ## Description 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 Input: p = [1,2,3], q = [1,2,3] Output: true Input: p = [1,2], q = [1,null,2] Output: false ## Constraints The number of nodes in both trees is in the range [0, 100]. -10^4^ <= Node.val <= 10^4^ ## Answer 此題可藉由遞迴方式實現,一開始先檢查到底NULL的情況,然後直接從return那邊就可以檢查val是否相等,再來就是兩樹往下推。 ```Cin= /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ // 2022_05_02 bool isSameTree(struct TreeNode* p, struct TreeNode* q){ if(p == NULL && q == NULL){return true;} else if(p == NULL || q == NULL){return false;} else{ return (p->val == q->val) && isSameTree(p->left,q->left) && isSameTree(p->right,q->right); } } ``` ## Link https://leetcode.com/problems/same-tree/ ###### tags: `Leetcode`