一次过
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isSameTree(TreeNode *p, TreeNode *q) { 13 // Start typing your C/C++ solution below 14 // DO NOT write int main() function 15 if (!p && !q) return true; 16 if ((!p && q) || (p && !q)) return false; 17 return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 18 } 19 };
C#
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public bool IsSameTree(TreeNode p, TreeNode q) { 12 if (p == null && q == null) return true; 13 if (p == null || q == null) return false; 14 return p.val == q.val && IsSameTree(p.left, q.left) && IsSameTree(p.right, q.right); 15 } 16 }