解决面试题的思路
画图让抽象问题具体化
画图 。图形能使抽象的问题具体化、形象化,借以辅助自己观察和思考。
对于复杂问题,应聘者光用语言未必能说得清楚,这时候可以画出几幅图形,一边看图形,一边讲解,面试官就能轻松地理解应聘者的思路。
二叉树的镜像
请完成一个函数,输入一颗二叉树,二叉树输出它的镜像。
二叉树节点定义
struct ListNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
}
void MirrorRecursively(BinaryTreeNode *pNode)
{
if(pNode==nullptr)
return;
if(pNode ->m_pLeft==nullptr&&pNode->m_pRight ==nullptr)
return;
BinaryTreeNode *pTemp = pNode->m_pLeft;
pNode->m_pLeft = pNode->m_pRight;
pNode->m_pRight = pTemp;
if(pNode->m_pLeft)
MirrorRecursively(pNode->m_pLeft)
if(pNode->m_pRight)
MirrorRecursively(pNode->m_pRight)
}
树的镜像
面试题28:对称的二叉树
请实现一个函数,用来判断一颗二叉树是不是对称的。如果一颗二叉树和它镜像一样,那么它是对称的
bool isSymmertrical(BinaryTreeNode* pRoot)
{
return isSymmetrical(pRoot,pRoot)
}
bool isSymmertrical(BinaryTreeNode* pRoot1,BinaryTreeNode* pRoot2)
{
if(pRoot1 == nullptr&&pRoot2==nullptr)
return true;
if(pRoot1 == nullptr||pRoot2 == nullptr)
return false;
if(pRoot1->m_nValue != pRoot2->m_nValue)
return false;
return isSymmetrical(pRoot1->m_Left,pRoot2->m_pRight)
&& isSymmetrical(pRoot1->m_pRight,pRoot2->m_Left);
}