-
题目思路
题目来源 -
C++代码实现
/*
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 == NULL)
{
return pNode;
}
if(pNode->right != NULL)
{
//后继节点就是右子树上最左的节点
//找到后可提前返回
return GetLeftMost(pNode->right);
}
else
{
//通过x找到父节点p,若x是p的左子树,则x的后继节点为p,若x是p的右子树,则继续向上找
TreeLinkNode* parent = pNode->next;
while(pNode != parent->left && parent != NULL)
{
parent = parent->next;
pNode = pNode->next;
}
return parent;
}
}
private:
TreeLinkNode* GetLeftMost(TreeLinkNode* pNode)
{
while(pNode->left != NULL)
{
pNode = pNode->left;
}
return pNode;
}
};