same tree

same tree

Easy problem

most importan thing is don't forget false, when one of the two node is NULL.

 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         if ( !p && !q ) {
14             return true;
15         }
16         if ( !p ) {
17             return false;
18         }
19         if ( !q ) {
20             return false;
21         }
22         if ( p->val != q->val ) {
23             return false;
24         }
25         if ( !isSameTree(p->left,q->left) ) {
26             return false;
27         }
28         if ( !isSameTree(p->right,q->right) ) {
29             return false;
30         }
31         return true;
32     }
33 };

Loading Disqus comments...
Table of Contents