程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 面試題23:二叉樹中和為某一值的路徑

面試題23:二叉樹中和為某一值的路徑

編輯:C++入門知識

\

\


#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;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved