Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

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  bool isSymetricHelper(TreeNode* A, TreeNode* B)
11  {
12      if((A==NULL)&&(B==NULL))
13         return true;
14      if((A==NULL)||(B==NULL))
15         return false;
16      if(A->val!=B->val)
17         return false;
18      bool p=isSymetricHelper(A->left,B->right);
19      bool q=isSymetricHelper(A->right,B->left);
20      return p&&q;
21  }
22 class Solution {
23 public:
24     bool isSymmetric(TreeNode *root) {
25         // Start typing your C/C++ solution below
26         // DO NOT write int main() function
27         if(root==NULL)
28             return true;
29         return isSymetricHelper(root->left,root->right);
30     }
31 };
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