当前位置:编程学习 > C/C++ >>

面试题23:二叉树中和为某一值的路径

\

\


#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

struct BinaryTreeNode
{
	int  m_nValue;
	BinaryTreeNode *m_pLeft;
	BinaryTreeNode *m_pRight;
};

void FindPath(BinaryTreeNode *pRoot, int nSum, vector<int>& path)
{
	if (pRoot == NULL || nSum == 0)
	{
		return;
	}

	if (pRoot->m_nValue == nSum && pRoot->m_pLeft == NULL && pRoot->m_pRight == NULL)
	{
	  vector<int>::iterator iter = path.begin();
	  for (; iter!=path.end(); iter++)
	  {
		  cout << *iter << " ";
	  }
	  cout << pRoot->m_nValue << endl;
	  return;	  
	}
	
	path.push_back(pRoot->m_nValue);

	if (pRoot->m_pLeft != NULL)
	{
		FindPath(pRoot->m_pLeft, nSum-pRoot->m_nValue, path);
	}

	if (pRoot->m_pRight != NULL)
	{
		FindPath(pRoot->m_pRight, nSum-pRoot->m_nValue, path);
	}

	path.pop_back();
}

//以先序的方式构建二叉树,输入#表示结点为空
void CreateBinaryTree(BinaryTreeNode *&pRoot)
{
	int nNodeValue = 0;
	cin >> nNodeValue;	
	if (-1 == nNodeValue)
	{
		pRoot = NULL;
		return; 
	}
	else
	{
		pRoot = new BinaryTreeNode();
		pRoot->m_nValue = nNodeValue;
		CreateBinaryTree(pRoot->m_pLeft);
		CreateBinaryTree(pRoot->m_pRight);
	}
}

void PrintInOrder(BinaryTreeNode *&pRoot)
{
	if (pRoot != NULL)
	{
		PrintInOrder(pRoot->m_pLeft);
		cout << pRoot->m_nValue << " ";
		PrintInOrder(pRoot->m_pRight);
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	BinaryTreeNode *pRoot = NULL;
	CreateBinaryTree(pRoot);
	PrintInOrder(pRoot);
	cout << endl;
	vector<int> path;
	FindPath(pRoot, 22, path);
	system("pause");
	return 0;
}

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,