# 二叉树的下一个节点

## 题目描述

class Solution {
vector<TreeLinkNode*> vec;
public:
TreeLinkNode * GetNext(TreeLinkNode* pNode)
{
if (pNode == NULL) return NULL;
TreeLinkNode* temp = pNode;
while (temp->next != NULL)
{
temp = temp->next;
}
InOrder(temp);
for (vector<TreeLinkNode*>::iterator iter = vec.begin(); iter != vec.end(); iter++)
{
if (*iter == pNode)
{
iter++;
return *iter;
}
}
return NULL;
}
void InOrder(TreeLinkNode* node)
{
if (node == NULL) return;
InOrder(node->left);
vec.push_back(node);
InOrder(node->right);
}
};

1.pNode节点如果右子树存在，找到右子树中最下方的左节点

2.右子树不存在，依次向上寻找父节点，找到第一个节点，该节点的条件是：该节点的左子树包含pNode。

/*
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->right != NULL)
{
TreeLinkNode* node = pNode->right;
while(node->left != NULL)
{
node = node->left;
}
return node;
}
else if(pNode->next != NULL)
{
if(pNode == pNode->next->left)
{
return pNode->next;
}
else if(pNode == pNode->next->right)
{
TreeLinkNode* node = pNode->next;
while(node->next != NULL)
{
if(node == node->next->left)
{
return node->next;
}
else if(node == node->next->right)
{
node = node->next;
}
}
return NULL;
}
}
return NULL;
}
};


class Solution {
private:
TreeLinkNode* res = NULL;
bool jug = false;
bool findRes = false;
public:
TreeLinkNode* GetNext(TreeLinkNode* pNode)
{
if(pNode == NULL)
{
return pNode;
}
TreeLinkNode* nodeToGetRoot = pNode;
while(nodeToGetRoot->next != NULL)
{
nodeToGetRoot = nodeToGetRoot->next;
}
InOrder(nodeToGetRoot,pNode);
return res;
}
void InOrder(TreeLinkNode* node,TreeLinkNode* &pNode)
{
if(node == NULL)
{
return;
}
InOrder(node->left,pNode);
//cout<<node->val<<endl;
if(jug && !findRes)
{
res = node;
findRes = true;
return;
}
if(node == pNode)
{
jug = true;
//cout<<"it is pNode"<<endl;
}
InOrder(node->right,pNode);
}
};