Prove safety face questions offer the next node binary tree 8

Problem: Given a binary tree and a node which is, 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.

Input: a node pointer in the binary tree

Output: pointer to the next node

Ideas:

When a node has a right child , it is the next node in the right subtree of the left-most node.

When a node is not the right sub-tree , it is the parent of the left son , it's the next node parent node.

When a node is not the right sub-tree , it is the parent of the right son , it is either the next node (retroactive up the parent, until you find a node as its parent node of the left subtree), either as ( If not retroactive, compared nullptr).

Code:

/*
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->next==nullptr)  初始为了只有一个节点,考虑,但其实是多虑了,反而会影响判断。
        //    return nullptr;
        TreeLinkNode* result;
        if(pNode->right!=nullptr)
        {
            result = pNode->right;
            while(result->left!=nullptr)
            {
                result = result->left;
            }
            return result;
        }
        if(pNode->next!=nullptr&&pNode->next->left==pNode)
            return pNode->next;
        if(pNode->next!=nullptr&&pNode->next->right==pNode)  // 这里不能用else,else包含的情况太多了
        {
            if(pNode->next!=nullptr)
                result = pNode->next;
            while(result->next!=nullptr&&result->next->right==result)
            {
                result= result->next;
            }
            return result->next;
        }
        return nullptr;
    }
};

The above second and third clauses if it may be replaced by the following code.

 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;
    }

 

Complexity Analysis: time complexity of O (n), the spatial complexity is O (1).

Topic: Another idea: The reduction sequence preorder binary tree . Disadvantages: will increase the space complexity, little introduction here.

 
Published 56 original articles · won praise 10 · views 6802

Guess you like

Origin blog.csdn.net/qq_22148493/article/details/104345775