I. Questions
Given a binary tree and one of its nodes, how can we find the next node in the ascending traversal order? In addition to two pointers pointing to the left and right child nodes, the nodes in the tree also have a pointer pointing to the parent node.
Ii. Ideas
After analyzing the questions, we found that the nodes to be processed only have three states. We can process them separately:
- The node to be processed has the right subtree. Then its next node is the leftmost child node of its right subtree, for example, the next node of Node 3 is 8;
- The node to be processed has no right subtree and is the left node of the parent node. Then its next node is its parent node, for example, node 5's next node is 3;
- The node to be processed has no right subtree and is the right node of the parent node. We can traverse up along its parent node until we find such a node, which is the left child of its parent node, then the parent node of the node is the requested node, for example, the next node of node 6 is 1.
Iii. Code
BinaryTreeNode* GetNext(BinaryTreeNode* pNode){ if(pNode == nullptr) return nullptr; BinaryTreeNode* pNext = nullptr; if(pNode->m_pRight != nullptr){ BinaryTreeNode* pRight = pNode->m_pRight; while(pRight->m_pLeft != nullptr) pRight = pRight->m_pLeft; pNext = pRight; } else if(pNode->m_pParent != nullptr){ BinaryTreeNode* pCurrent = pNode; BinaryTreeNode* pParent = pNode->m_pParetn; while(pParent != nullptr && pNode = pParent->m_pRight){ pCurrent = pParent; pParent = pParent->m_pParent; } pNext = pParent; } return pNext;}
4. Question site
- Measure the test taker's knowledge about binary tree traversal. Only by having a deep understanding of the binary tree traversal algorithm can the applicant accurately find the next node for the central traversal of each node.
- Measure the test taker's knowledge about complex problem analysis. Candidates can design a feasible algorithm only by drawing a binary tree structure and finding the law of the next node in the middle-order traversal through specific examples.
Interview question 8: Next node of a binary tree