題目描述
請設計一個算法,尋找二叉樹中指定結點的下一個結點(即中序遍歷的後繼)。
給定樹的根結點指針TreeNode* root和結點的值int p,請返回值爲p的結點的後繼結點的值。保證結點的值大於等於零小於等於100000且沒有重複值,若不存在後繼返回-1。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Successor {
public:
int findSucc(TreeNode* root, int p)
{
if(root==NULL) return -1;
int flag=0;
stack<TreeNode*>tmpStack;
TreeNode* pNode=root;
while(pNode||!tmpStack.empty())
{
while(pNode)
{
tmpStack.push(pNode);
pNode=pNode->left;
}
if(!tmpStack.empty())
{
if (p==(tmpStack.top()->val))
{
flag=1;
}
else if(flag==1)
{
return (tmpStack.top()->val);
}
pNode=tmpStack.top()->right;
tmpStack.pop();
}
}
return -1;
}
};