Leetcode100.相同的树
题目描述
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 13 class Solution { 14 public: 15 bool isSameTree(TreeNode* p, TreeNode* q) { 16 if (p == nullptr && q == nullptr) { 17 return true; 18 } else if (p == nullptr || q == nullptr) { 19 return false; 20 } else if (p->val != q->val) { 21 return false; 22 } else { 23 return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 24 } 25 } 26 };