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