《leetCode》:Symmetric Tree

来源:互联网 发布:淘宝上有纯粮食酒吗 编辑:程序博客网 时间:2024/06/06 02:05

题目

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).For example, this binary tree is symmetric:    1   / \  2   2 / \ / \3  4 4  3But the following is not:    1   / \  2   2   \   \   3    3Note:Bonus points if you could solve it both recursively and iteratively.

思路

将左子树的左节点的值与右子树的右节点的值进行比较,而将左子树的右节点的值与右子树的左节点的值进行比较即可。

实现代码如下:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */bool isSym(struct TreeNode* leftroot,struct TreeNode* rightroot){    if(leftroot==NULL&&rightroot==NULL){        return true;    }    else if(leftroot==NULL&&rightroot!=NULL||(leftroot!=NULL&&rightroot==NULL)) {        return false;    }    return (leftroot->val==rightroot->val)&&isSym(leftroot->left,rightroot->right)&&isSym(leftroot->right,rightroot->left);}bool isSymmetric(struct TreeNode* root) {    return isSym(root,root) ; }
1 0