剑指offer:对称的二叉树

题目描述:

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

思路分析:

二叉树的镜像就是左右相反,对称二叉树即镜像相等。利用一个递归函数,输入为两颗树,若同为空,则对称。若一棵为空,一棵不为空,则不对称。若二者的指不相等,则不对称,若树1的左子树和树2的右子树相等且树1的右子树和树2的左子树相等,则对称。

代码:

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };
10 */
11 class Solution {
12 public:
13     bool symmetric(TreeNode* pRoot1, TreeNode* pRoot2)
14     {
15         if(pRoot1 == nullptr && pRoot2 == nullptr)
16             return true;
17         if(pRoot1 == nullptr || pRoot2 == nullptr)
18             return false;
19         if(pRoot1->val != pRoot2->val)
20             return false;
21         return (symmetric(pRoot1->left, pRoot2->right) && symmetric(pRoot2->left, pRoot1->right));
22         
23     }
24     bool isSymmetrical(TreeNode* pRoot)
25     {
26         if(pRoot == nullptr)
27             return true;
28         return symmetric(pRoot, pRoot);
29     }
30 
31 };
原文地址:https://www.cnblogs.com/LJ-LJ/p/11587821.html