剑指OFFER 二叉树的下一个结点
/*
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* target_node = NULL;
TreeLinkNode* res_node = NULL;
bool ok = false;
void recur(TreeLinkNode* node)
{
if(node == NULL){
return ;
}
recur(node->left);
if(ok == true){
res_node = node;
ok = false;//avoid next entering
}
if(node == target_node){
ok = true;
}
recur(node->right);
}
TreeLinkNode* GetNext(TreeLinkNode* pNode)
{
//handle special case
if(pNode == NULL)return NULL;
//initialize
target_node = pNode;
//get root node
TreeLinkNode* root = pNode;
while(root->next != NULL){
root = root->next;
}
//recurly traverse to find the next node
recur(root);
return res_node;
}
};