The next node of the binary tree to prove safety offer

Title Description

And wherein a given binary tree of a node, find the next node in a preorder traversal order and returns. Note that the node in the tree contains not only the left and right child nodes, the parent node contains a pointer pointing to.

Thinking

First, determine whether the node has no right child nodes, if any, has been traversed the left child and right child nodes, until a NULL, then return to the left child node
if the node is no right child nodes, then up a layer, determine whether the node is not the parent left child node, if the parent node is returned, if not, then continue up until there is no parent node, indicating that this node is the last node, or NULL

Code

class Solution {
public:
    TreeLinkNode* GetNext(TreeLinkNode* pNode)
    {
        if(pNode == NULL)
            return NULL;
        if(pNode->right != NULL)
        {
            TreeLinkNode* tmp = pNode->right;
            while(tmp->left != NULL)
                tmp = tmp->left;
            return tmp;
        }
        while(pNode->next != NULL)
        {
            TreeLinkNode* tmp = pNode->next;
            if(tmp->left == pNode)
                return tmp;
            pNode = tmp;
        }
        return NULL;
    }
};
Published 85 original articles · won praise 0 · Views 400

Guess you like

Origin blog.csdn.net/weixin_38312163/article/details/104810516