面试题17:如何判断二叉树是否是对称二叉树?

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.

confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.

 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 isSymmetric(TreeNode* left,TreeNode* right){
13         if(left == nullptr && right == nullptr){
14             return true;
15         }else if(left == nullptr || right == nullptr){
16             return false;
17         }else if(left->val == right->val){
18             if(isSymmetric(left->left,right->right) && isSymmetric(left->right,right->left)){
19                 return true;
20             }else{
21                 return false;
22             }
23         }else{
24             return false;
25         }
26     }
27     bool isSymmetric(TreeNode *root) {
28         if(root == nullptr) return true;
29         return isSymmetric(root->left,root->right);
30     }
31 };

 

posted @ 2017-05-15 22:50  wxquare  阅读(626)  评论(0编辑  收藏  举报