【Leetcode】之Symmetric Tree

来源:互联网 发布:mac怎么删除文件夹 编辑:程序博客网 时间:2024/06/06 02:32

一.问题描述

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

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

二.我的解题思路

如果一个二叉树是中心对称的,那么它左孩子的右子树一定是等他它右孩子的左子树,同理反过来亦然。所以直接使用判断两棵树是否相等的程序,测试通过的程序如下:
/** * 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 isSymmetric(TreeNode* root) {        if(!root) return true;        int res = isEqual(root->left,root->right);        return res;    }        bool isEqual(TreeNode* n1, TreeNode* n2){        if(!n1 && !n2) return true;        if((!n2 && n1) || (!n1 && n2)) return false;        if(n1->val!=n2->val) return false;        else            return isEqual(n1->left,n2->right) && isEqual(n1->right,n2->left);    }};



0 0
原创粉丝点击