重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
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
代码如下:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //思路: //1.判断root是否为空,若空则返回true,否则false; //2.判断root->left,root->right是否同时为空,若为空则返回true; //3.判断root->left,root->right同时不为空时,将root->right反转, //然后判断新root->right和root->left是否为相同的树。 class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { bool childResult; if( NULL == p && NULL == q) return true; if( NULL != p && NULL != q && p->val == q->val) { return childResult = isSameTree(p->left,q->left) && isSameTree(p->right,q->right); } return false; } void reverseTree(TreeNode* root) { if(!root) return; TreeNode *p,*q; p = root->left; q = root->right; root->left = q; root->right = p; reverseTree(root->left); reverseTree(root->right); } bool isSymmetric(TreeNode* root) { if( (NULL == root) || ( NULL == root->left && NULL == root->right) ) return true; if(NULL != root->left && NULL != root->right) { reverseTree(root->right); return isSameTree(root->left,root->right); } return false; } };