二叉樹尋找給定結點p的下一個結點

題目描述

請設計一個算法,尋找二叉樹中指定結點的下一個結點(即中序遍歷的後繼)。

給定樹的根結點指針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;
	}
};


發佈了41 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章