--- tags: leetcode --- # [100. Same Tree](https://leetcode.com/problems/same-tree/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isSameTree(TreeNode *p, TreeNode *q) { if (p == nullptr && q == nullptr) { return true; } if (p == nullptr || q == nullptr) { return false; } if (p->val != q->val) { return false; } return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } }; ``` ## Time Complexity $O(n)$ $n$ is the number of nodes in the binary tree. ## Space Complexity $O(H)$ $H$ is the height of the binary tree. # Miscellane <!-- # Test Cases ``` [1,2,3] [1,2,3] ``` ``` [1,2] [1,null,2] ``` ``` [1,2,1] [1,1,2] ``` ``` [0,-5] [0,-8] ``` ``` [10,5,15] [10,5,null,null,15] ``` ``` [1,1] [1,null,1] ``` ``` [] [0] ``` -->