101. Symmetric Tree

来源:互联网 发布:阿里云哪个区域好 编辑:程序博客网 时间:2024/06/06 02:29

题目:

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.

思路:

这道题目,其实很简单,只要稍稍修改我前一篇博客的函数,并调用就好了Same Tree

代码:

/** * 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 {public:    bool isSameTree(TreeNode* p, TreeNode* q) {          if(p==NULL&&q==NULL)              return true;          else if(p==NULL&&q!=NULL)              return false;          else if(p!=NULL&&q==NULL)              return false;          else          {              if(p->val!=q->val)                  return false;              else                  return isSameTree(p->left,q->right)&&isSameTree(p->right,q->left);          }                }      bool isSymmetric(TreeNode* root) {        TreeNode* temp = root;        return isSameTree(root,temp);           }};


原创粉丝点击