Niuke.com's sword refers to offer-the next node of the binary tree

topic description

Given a binary tree and a node in it, find the next node in the inorder traversal order and return it. Note that the nodes in the tree not only contain left and right child nodes, but also contain pointers to parent nodes.


/*
struct TreeLinkNode {
    int val;
    struct TreeLinkNode *left;
    struct TreeLinkNode *right;
    struct TreeLinkNode *next;
    TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {
        
    }
};
*/
class Solution {
public:
    //如果存在右孩子,那么答案就是右孩子结点一直向左到底,
    //否则就向上找父节点,知道当前节点是父节点的左孩子,
    //答案就是父节点,如果一直到根节点都没有就返回空指针
    TreeLinkNode* GetNext(TreeLinkNode* pNode)
    {
        if (pNode == nullptr)
            return nullptr;
        if (pNode->right != nullptr)
        {
            pNode = pNode->right;
            while (pNode->left != nullptr)
                pNode = pNode->left;
            return pNode;
        }
        else
        {
            while (pNode->next != nullptr)
            {
                if (pNode->next->left == pNode)
                    return pNode->next;
                pNode = pNode->next;
            }
            return nullptr;
        }
    }
};

Guess you like

Origin blog.csdn.net/yhn19951008/article/details/79433822