Binary tree next node

[Problems] Given a binary tree and a node which, 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] This question is very deceptive parent pointer is not called parent, called the next, it is too wonderful, but does not matter, the next node traversal sequence is divided into two situations:

Case 1: there is the right subtree of the node, the left-most node of the right subtree of the node is the next node, we traverse to find it!

Case 2: the right subtree of the node does not exist, it can be divided into two cases

1. If the node is the right node, you need to have to traverse upwards until it finds a node is the left node, stop, left the parent node is the next node.

2. If the node is the left node, the parent node to the next node!

/*
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;
        TreeLinkNode* pNext = nullptr;
        if(pNode->right != nullptr)     //情况一:有右子树
        {
            TreeLinkNode * = pNode- Pright> right;
             the while (! PRight-> left = nullptr a)     
                Pright = pRight-> left;     // Find the leftmost right subtree node 
            pNext = Pright; 
        } 
        the else  IF (pNode-> Next =! nullptr a)    // case 2: the right subtree is empty 
        { 
            TreeLinkNode * = pCurrent • pNode; 
            TreeLinkNode * = pNode- pParent> Next;
             the while ! (pParent = nullptr a && pCurrent pParent- ==> right) 
                 // 2.1 empty right subtree and the node is the right node, you have to find up until the left node of the parent node node
                 //The parent node of the node to the next node 
            { 
                pCurrent = pParent; 
                pParent = pParent-> Next; 
            } 
            // 2.2 is empty and the right subtree is the left node, the parent node is the next node 
            pNext = pParent; 
        } 
         return pNext ; 
    } 
};

 

Guess you like

Origin www.cnblogs.com/zhudingtop/p/11456043.html