二叉树中,找到从根节点到某一个节点的路径

源码转自

http://blog.csdn.net/hackbuteer1/article/details/6686858

1。 首先是检测某个节点时候在某个二叉树中出现过。

/*
// If the tree with head pHead has a node pNode, return true.
// Otherwise return false.
*/
bool HasNode(TreeNode* pHead, TreeNode* pNode)
{
	if(pHead == pNode)
		return true;
	bool has = false;
	if(pHead->m_pLeft != NULL)
		has = HasNode(pHead->m_pLeft, pNode);
	if(!has && pHead->m_pRight != NULL)
		has = HasNode(pHead->m_pRight, pNode);
	return has;
}


2. 从根节点到某一个节点的路径

/*
// Get the path form pHead and pNode in a tree with head pHead
*/
bool GetNodePath(TreeNode* pHead, TreeNode* pNode, std::list<TreeNode*>& path)
{
	if(pHead == pNode)
		return true; 

	path.push_back(pHead); 

	bool found = false;
	if(pHead->m_pLeft != NULL)
		found = GetNodePath(pHead->m_pLeft, pNode, path);
	if(!found && pHead->m_pRight)
		found = GetNodePath(pHead->m_pRight, pNode, path);
	if(!found)
		path.pop_back();
	return found;
}