华为2020届软件开发二面代码题

如何判断一棵树是否为镜像?

镜像是指从根节点竖直向下切割,左右镜像对称。

在这里插入图片描述

递归:
一棵树是镜像的,那么它的左右子树肯定是镜像的。

左右子树要满足镜像,必须满足:

  1. 左右子树的值相等。
  2. 左子树的右子树与右子树的左子树镜像。
  3. 左子树的左子树与右子树的右子树镜像。

满足以上条件即可,利用递归判断。

typedef int ElementType;
class BinaryTree
{
public:
	ElementType Val;
	BinaryTree* LeftChild;
	BinaryTree* RightChild;
	BinaryTree(ElementType val = 0)
	{
		Val = val;
		LeftChild = NULL;
		RightChild = NULL;
	}

	bool isMirror(const BinaryTree* BT)
	{
		return isMirrorLeftRight(BT->LeftChild, BT->RightChild);
	}

	bool isMirrorLeftRight(const BinaryTree* LeftChild, const BinaryTree* RightChild)
	{
		if (LeftChild == NULL && RightChild == NULL)
			return true;
		else if (LeftChild == NULL || RightChild == NULL)
			return false;
		else
		{
			if (LeftChild->Val != RightChild->Val)
				return false;
			else
				return (isMirrorLeftRight(LeftChild->LeftChild, RightChild->RightChild) && isMirrorLeftRight(LeftChild->RightChild, RightChild->LeftChild));
		}
	}
};

信息来自同实验室应届硕士毕业生。

原创文章 17 获赞 4 访问量 3965

猜你喜欢

转载自blog.csdn.net/weixin_37524256/article/details/101117931