LeetCode101 Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). (Easy)

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

分析:

递归的思路,helper函数用于判定两个子树是否对称,其判别的标准是两个子树的根节点值相等,且

子树1的左孩子与子树2的右孩子对称,子树1的右孩子与子树2的左孩子对称。

以此递归下去,即可得到结果。

代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11     bool helper(TreeNode* t1, TreeNode* t2) {
12         if (t1 == nullptr && t2 == nullptr) {
13             return true;
14         }
15         if ( (t1 == nullptr && t2 != nullptr) || (t1 != nullptr && t2 == nullptr) ) {
16             return false;
17         }
18         if (t1 -> val != t2 -> val) {
19             return false;
20         }
21         else 
22             return helper(t1 -> left, t2 -> right) && helper(t1 -> right, t2 -> left);
23     }
24 public:
25     bool isSymmetric(TreeNode* root) {
26         if (root == nullptr) {
27             return true;
28         }
29         return helper(root -> left, root -> right);
30     }
31 };
 
原文地址:https://www.cnblogs.com/wangxiaobao/p/6033437.html