剑指offer 对称的二叉树

题目描述

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
 
思路:二叉树的问题大部分是递归解法,联想最基本的情况进行分析,如果是
 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 helper(TreeNode* root1,TreeNode* root2){
14         if(root1 == nullptr && root2 == nullptr){
15             return true;
16         }
17         if(root1 == nullptr || root2 == nullptr){
18             return false;
19         }
20         if(root1 -> val != root2 -> val){
21             return false;
22         }
23         
24         return helper(root1 -> left,root2 -> right) && helper(root1 -> right,root2 -> left);
25         
26     }
27     bool isSymmetrical(TreeNode* pRoot){
28         bool result = false;
29         if(pRoot == nullptr){
30             return true;
31         }
32         result = helper(pRoot,pRoot);
33         return result;
34     }
35 
36 };
原文地址:https://www.cnblogs.com/dingxiaoqiang/p/7512400.html