LeetCode 101 Symmetric Tree 判断一颗二叉树是否是镜像二叉树

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
    1
   / \
  2   2
 / \   / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:
    1
   / \
  2   2
   \   \
   3    3
Note:
Bonus points if you could solve it both recursively and iteratively.

 1 /**
 2  * Definition for a binary tree node.
 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* root) {
13         if(root==nullptr)
14             return true;
15         return helper(root->left,root->right);
16     }
17     bool helper(TreeNode* left,TreeNode* right)
18     {
19         if(!left&&!right)
20             return true;
21         else if(!left||!right)
22             return false;
23         else if(left->val!=right->val)
24             return false;
25         else
26             return helper(left->left,right->right)&&helper(left->right,right->left);
27     }
28 };

 

posted on 2018-03-15 11:22  lina2014  阅读(108)  评论(0编辑  收藏  举报

导航