lintcode 1360. 对称树

给定二叉树,返回它是否是自身的镜像(即这棵二叉树是否对称)。

样例
样例1

输入: {1,2,2,3,4,4,3}
输出: true
解释:
    1
   / \
  2   2
 / \ / \
3  4 4  3
{1,2,2,3,4,4,3}这棵二叉树是对称的
样例2

输入: {1,2,2,#,3,#,3}
输出: false
解释:
    1
   / \
  2   2
   \   \
   3    3
很显然这棵二叉树并不对称
挑战
用递归和迭代的方法来解决这个问题(2种解法)
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: root of the given tree
     * @return: whether it is a mirror of itself 
     */
    bool isSymmetric(TreeNode * root) {
        // Write your code here
        if(root==NULL) return true;
        return recursion(root->left,root->right);
    }
    bool recursion(TreeNode*root1,TreeNode*root2)
    {
        if(root1==NULL&&root2==NULL) return true;
        else if(root1==NULL||root2==NULL) return false;
        else if(root1->val!=root2->val) return false;
        return recursion(root1->left,root2->right)&&recursion(root1->right,root2->left);
    }
};
发布了369 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43981315/article/details/104002899
今日推荐