【简单算法】28.对称二叉树

题目:

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / 
  2   2
 /  / 
3  4 4  3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / 
  2   2
      
   3    3
说明:

如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

解题思路:

递归

1.判断左孩子的值与右孩子的值相等,同时判断左子树和右子树是否都为镜像树。

源代码:

/**
 * 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 isSymmetricTree(TreeNode* root1,TreeNode* root2){
        if((root1&&!root2)||(!root1&&root2)){
            return false;
        }
        
        if(root1 == NULL && root2 == NULL){
            return true;
        }
        
        if(root1->val != root2->val){
            return false;
        }
        
        return isSymmetricTree(root1->left,root2->right)&&isSymmetricTree(root1->right,root2->left);
    }
    
    bool isSymmetric(TreeNode* root) {
        if(root == NULL){
            return true;
        }
        
        return isSymmetricTree(root->left,root->right);
    }
};
原文地址:https://www.cnblogs.com/mikemeng/p/8987781.html