面试题28:对称的二叉树

对称的二叉树

题目描述

判断一个二叉树是不是对称的



bool isSymmetrical(BinaryTreeNode *pRoot)
{
	return isSymmetrical(pRoot, pRoot);
}

bool isSymmetrical(BinaryTreeNode  *p, BinaryTreeNode *q)
{
	if(p==nullptr && q == nullptr)
		return true;
	if(p==nullptr || q == nullptr)
		return false;
	if(p->value != q->value)
		return false;
	return isSymmetrical(p->left, q->right) && isSymetrical(p->right,q->left);
}

leetcode

  1. 对称二叉树
    给定一个二叉树,检查它是否是镜像对称的
class Solution {
public:
    bool isSymmetricCore(TreeNode *p, TreeNode *q)
    {
        if(p==nullptr && q==nullptr) return true;
        if(p==nullptr || q==nullptr) return false;
        if(p->val != q->val) return false;
        return isSymmetricCore(p->left, q->right) && isSymmetricCore(p->right, q->left);
    }
    
    bool isSymmetric(TreeNode* root) {
        return isSymmetricCore(root, root);
    }
};

执行用时 : 12 ms, 在Symmetric Tree的C++提交中击败了93.87% 的用户
内存消耗 : 15 MB, 在Symmetric Tree的C++提交中击败了78.58% 的用户

发布了68 篇原创文章 · 获赞 2 · 访问量 6187

猜你喜欢

转载自blog.csdn.net/qq_30050175/article/details/90550954