zoukankan      html  css  js  c++  java
  • 二叉树的下一个节点

    //==================================================================
    // 《剑指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;
    }
    

    分析过程:

  • 相关阅读:
    蘑菇街
    康拓展开
    CSS学习笔记
    专业名词
    专业名字
    01背包问题
    将bbr功能合入到centos7.3
    How to Identify User&Password of DataBase safely in SQL statement?
    tips for private constructor
    all Key Word of C#
  • 原文地址:https://www.cnblogs.com/Lothlorien/p/10334597.html
Copyright © 2011-2022 走看看