//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题8:二叉树的下一个结点
// 题目:给定一棵二叉树和其中的一个结点,如何找出中序遍历顺序的下一个结点?
// 树中的结点除了有两个分别指向左右子结点的指针以外,还有一个指向父结点的指针。
#include <iostream>
struct BinaryTreeNode
{
    int m_nValue;
    BinaryTreeNode* m_pLeft;
    BinaryTreeNode* m_pRight;
    BinaryTreeNode* m_pParent;
};

// 找出中序遍历顺序的下一个结点
BinaryTreeNode* GetNext(BinaryTreeNode* pNode) {
    // 空指针检查
    if (pNode == nullptr) {
        return nullptr;
    }

    BinaryTreeNode* pNext = nullptr;
    if (pNode->m_pRight != nullptr) {
        pNext = pNode->m_pRight;
        while (pNext->m_pLeft != nullptr) {
            pNext = pNext->m_pLeft;
        }
    } else if (pNode->m_pParent != nullptr) {
        // 使用两个指针,一个指向当前节点,一个指向当前节点的父节点,这样就可以判断当前节点和父节点的关系
        BinaryTreeNode* pCurrent = pNode;
        BinaryTreeNode* pParent = pNode->m_pParent;
        // 这里是移动指针,走过不符合条件的节点
        while(pParent != nullptr && pCurrent == pParent->m_pRight){
            pCurrent = pParent;
            pParent = pParent->m_pParent;
        }

        pNext = pParent; // 这里是有可能为空指针的(当没有下一个节点时)
    }

    return pNext;
}

// 构建二叉树
BinaryTreeNode* CreateBinaryTreeNode(int value) {
    BinaryTreeNode* pNode = new BinaryTreeNode();
    pNode->m_nValue = value;
    pNode->m_pLeft = nullptr;
    pNode->m_pRight = nullptr;
    pNode->m_pParent = nullptr;
    
    return pNode;
}

分析过程:

posted on 2019-01-29 16:17  被杜撰的风  阅读(105)  评论(0编辑  收藏  举报