面试题8:找出中序遍历的下一个节点

2018-11-12  本文已影响0人  修司敦
给定一颗二叉树和其中的一个节点,找出中序遍历序列中的下一个节点。树节点的结构声明为
struct BTreeNode
{
    int        value;
    BTreeNode* pLeft;
    BTreeNode* pRight;
    BTreeNode* pParent;
};

解析:分两种情况:


答案:

inline bool isRoot(BTreeNode *pNode)
{
    if (nullptr == pNode) return false;
    return nullptr==pNode->pParent;
}

inline bool isLeft(BTreeNode *pNode)
{
    if (nullptr == pNode) return false;
    if (nullptr != pNode->pParent)
        return pNode == pNode->pParent->pLeft;
    return false;
}

inline bool isRight(BTreeNode *pNode)
{
    if (nullptr == pNode) return false;
    if (nullptr != pNode->pParent)
        return pNode == pNode->pParent->pRight;
    return false;
}

BTreeNode* GetNext(BTreeNode* pNode)
{
    if (pNode == nullptr) return nullptr;

    //if this node has a right subtree
    if (nullptr != pNode->pRight)
    {
        auto pTemp = pNode->pRight;
        while (nullptr != pTemp->pLeft) pTemp = pTemp->pLeft;
        return pTemp;
    }

    //if this node doesn't have a right subtree
    else
    {
        if (isRoot(pNode)) return nullptr;
        else if (isLeft(pNode))
            return pNode->pParent;
        else if (isRight(pNode))
        {
            while (isRight(pNode)) pNode = pNode->pParent;
            if (isLeft(pNode)) return pNode->pParent;
            else if (isRoot(pNode)) return nullptr;
        }
    }

    return nullptr;
}
上一篇 下一篇

猜你喜欢

热点阅读