二叉树其他面试题:二叉树面试题——上
十二、二叉树的镜像
题目:请完成一个函数,输入一棵二叉树,该函数输出它的镜像。二叉树节点定义如下:
typedef struct BinaryTreeNode
{
struct BinaryTreeNode* _left;
struct BinaryTreeNode* _right;
BTSTDataType _data;
}BTNode;
< code >
void MirrorRecursively(BTNode* pNode)
{
if (NULL == pNode)
return;
if(pNode->_left == NULL && pNode->_right == NULL)
return;
BTNode* tmp = pNode->_left;
root->_left = pNode->_right;
pNode->_right = tmp;
if(pNode->_left)
MirrorRecursively(pNode->_left);
if(pNode->_right)
MirrorRecursively(pNode->_right);
}
十三、判断两颗二叉树是否相同
int TwoBTreeIsSame(BTNode* root1, BTNode* root2) //判断两颗二叉树是否相同
{
if (NULL == root1 && NULL == root2)
{
return 1;
}
else if (NULL == root1 || NULL == root2)
{
return 0;
}
return TwoBTreeIsSame(root1->_left, root2->_left) && TwoBTreeIsSame(root1->_right, root2->_right);
}
十四、找寻两个节点的最低公共祖先
BTNode* FindLCA(BTNode* root, BTNode* target1, BTNode* target2) //找寻两个节点的最低公共祖先
{
if (NULL == root)
{
return root;
}
else if (root == target1 || root == target2)
{
return root;
}
BTNode* left = FindLCA(root->_left, target1, target2);
BTNode* right = FindLCA(root->_right, target1, target2);
if (NULL != left && NULL != right) //两个节点分别在root的左子树和右子树
{
return root;
}
return left ? left : right;
}
十五、将二叉搜索树转换成双向链表
详细解析参照:《剑指offer》面试题36:将二叉搜索树转换成双向链表
BinaryTreeNode* Convert(BinaryTreeNode* pRootOfTree)
{
// 记录链表的尾节点
BinaryTreeNode* pLastNodeInList = nullptr;
// 把二叉树转换成双向链表
ConvertNode(pRootOfTree, &pLastNodeInList);
// 找到双向链表的头结点
BinaryTreeNode* pHeadOfList = pLastNodeInList;
while (pHeadOfList != nullptr && pHeadOfList->m_pLeft != nullptr)
{
pHeadOfList = pHeadOfList->m_pLeft;
}
// 返回双向链表的头结点
return pHeadOfList;
}
void ConvertNode(BinaryTreeNode* pNode, BinaryTreeNode** pLastNodeInList)
{
if (pNode == nullptr)
return;
BinaryTreeNode* pCurrent = pNode;
// 往左子树递归, 从最左节点开始链起
if (pCurrent->m_pLeft != nullptr)
{
ConvertNode(pCurrent->m_pLeft, pLastNodeInList);
}
// 处理当前节点
//将当前节点的左指针指向已经转换好的链表的尾节点
pCurrent->m_pLeft = *pLastNodeInList;
//将已经转换好的链表的尾节点的右指针指向当前节点
if (*pLastNodeInList != nullptr)
{
(*pLastNodeInList)->m_pRight = pCurrent;
}
//更新已经转换好的链表的尾节点
*pLastNodeInList = pCurrent;
// 递归去处理右子树
if (pCurrent->m_pRight != nullptr)
{
ConvertNode(pCurrent->m_pRight, pLastNodeInList);
}
}