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

题目的要求就是说,查看一颗二叉树是否为中心对称的。
这道题目还是很简单的。首先判断初始条件:root不存在,或者只有单独的root时。返回ture。
然后我们可以递归二叉树,看是否中心对称(写一个递归函数)
 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 dfs(TreeNode *left,TreeNode *right)
13 
14     {
15 
16         if(!left && !right) return true;//需要先判断这个,不然val那个可能会出现RE
17 
18         if((left && !right) || (!left && right) || (left->val!=right->val)) return false;
19 
20         return dfs(left->left,right->right) && dfs(left->right,right->left);
21 
22     }
23     bool isSymmetric(TreeNode *root) {
24         if(root==NULL || (!root->left && !root->right)) return true;
25         return dfs(root->left,root->right);
26     }
27 };

 

posted on 2015-03-24 18:46  何氏小萌  阅读(111)  评论(0)    收藏  举报