101. Symmetric Tree

来源:互联网 发布:淘宝平台账务处理 编辑:程序博客网 时间:2024/05/09 23:33

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

这道题的思路和上道题思路基本一致,都是利用递归来解决,写一个leftandright函数来递归

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution 
{
private:
    bool leftandright(TreeNode* left,TreeNode* right)

    {

        if(left==NULL&&right==NULL)

         return true;

       if(left==NULL&&right!=NULL)

         return false;

      if(left!=NULL&&right==NULL)

        return false;

      if(left!=NULL&&right!=NULL&&left->val!=right->val)

        return false;

       else

       return  leftandright(left->left,right->left)&&leftandright(left->right,right->right);

    

    }

public:

  bool isSymmetric(TreeNode* root)

    {

        if(root==NULL)

        return false;

       else

       return  leftandright(root->left,root->right);

    }

};

    




















原创粉丝点击