Binary tree to the next node (preorder)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/q943520218/article/details/100566440

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.

struct TreeLinkNode {
    int val;
    struct TreeLinkNode *left;
    struct TreeLinkNode *right;
    struct TreeLinkNode *next;
    TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {
        
    }
};

Since there is a parent node, so long you can not traverse the entire tree to get the results

Points can be discussed

First, in order traversal, the first left sub-tree root node in the right subtree

1, in order to traverse node one node will be the left and right subtree subtree left subtree of a node is empty (left subtree node if present)

2, there are two cases when a right subtree of a node does not exist,

      (1) The node is a parent node with a left subtree (then the parent node is a node after preorder)

      (2) until the root node in the right subtree, then the node is preferably a node in the node traversal sequence is null

To achieve the following:

    class Solution {
    public:
        TreeLinkNode* GetNext(TreeLinkNode* pNode)
        {
            if (pNode->right != nullptr)
            {
                return pNode->right;
            }

            while (pNode->next)
            {
                if (pNode->next->left == pNode) // 是左子树节点
                {
                    return pNode->next;
                }
                else
                {
                    pNode = pNode->next;
                }
            }

            return nullptr;
        }
    }

 

Guess you like

Origin blog.csdn.net/q943520218/article/details/100566440