Same Tree

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

C++:
01 /**
02  * Definition for binary tree
03  * struct TreeNode {
04  *     int val;
05  *     TreeNode *left;
06  *     TreeNode *right;
07  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
08  * };
09  */
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==NULL)&&(q==NULL))
16             return true;
17         if((p==NULL)||(q==NULL))
18             return false;
19         if(p->val!=q->val)
20             return false;
21         return (isSameTree(p->left,q->left))
22                 &&(isSameTree(p->right,q->right));
23     }
24 };
Advertisements
This entry was posted in Recursive, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s