LeetCode(51) Symmetric Tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/angelazy/article/details/48684295

题目描述

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

For example, this binary tree is symmetric:

symmetric tree

But the following is not:

not symmetric tree

判断一棵二叉树是否对称。

解题思路

根据题目要求,可以认为是树的层序遍历的一种应用。可以递归的判断树的左右子树是否相等。

  • 根节点直接递归判断左右子树即可;
  • 对于根节点一下的结点,需要判断
    • 左结点的左子树和右结点的右子树;
    • 左结点的右子树和右结点的左子树
/**
 * 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 isSame(TreeNode* left, TreeNode* right)
    {
        if(!left && !right) return true;
        if(left && !right || !left && right) return false;
        if(left->val != right->val) return false;
        return isSame(left->left, right->right) && isSame(left->right, right->left);
    }
    bool isSymmetric(TreeNode* root) {
        if(!root) return true;
        return isSame(root->left, root->right);
    }
};

猜你喜欢

转载自blog.csdn.net/angelazy/article/details/48684295