前进的道路不是一帆风顺的,要随时迎接挑战,敢于战胜困难!

坚持一下,找人聊聊天,释放一些压力!

 

在二元树中查找和为某一值的所有路径

#include <iostream>
#include <vector>
using namespace std;

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

int count=0; //print control

void FindPath(
 BinaryTreeNode* pTreeNode,
 int expectedSum,
 vector<int>& path,
 int& currentSum)
{
 if (!pTreeNode)
 {
  return;
 }
 
 currentSum+=pTreeNode->m_nValue;
 path.push_back(pTreeNode->m_nValue); 

 bool isLeaf=!(pTreeNode->m_pLeft)&&!(pTreeNode->m_pRight);

 if (currentSum==expectedSum && isLeaf)
 {
  vector<int>::iterator iter;
  for (iter=path.begin(); iter!=path.end(); iter++)
  {
   cout<<*iter<<'\t';
  }
  cout<<endl;
 }

 if (pTreeNode->m_pLeft)
 {
  FindPath(pTreeNode->m_pLeft, expectedSum, path, currentSum);
 }
 if (pTreeNode->m_pRight)
 {
  FindPath(pTreeNode->m_pRight, expectedSum, path, currentSum);
 }

 //when finish visiting a node and return to its parent node,
 //should delete this node from the path and
 //minus the node's value from the current sum
 currentSum-=pTreeNode->m_nValue;
 path.pop_back();
}

void AddTree(BinaryTreeNode** T, int num)
{
 if (*T==NULL)
 {
  *T=(BinaryTreeNode*)malloc(sizeof(BinaryTreeNode));
  (*T)->m_nValue=num;
  (*T)->m_pLeft=NULL;
  (*T)->m_pRight=NULL;
 }
 else if ((*T)->m_nValue>num)
 {
  AddTree(&((*T)->m_pLeft), num);
 }
 else
 {
  AddTree(&((*T)->m_pRight), num);
 }
}

void MidTraversal(BinaryTreeNode* T)
{
 if(T!=NULL)
 {
  MidTraversal(T->m_pLeft);
  count++;
  if (count%5==0)
  {
   cout<<T->m_nValue<<endl;
  }
  else
  {
   cout<<T->m_nValue<<"\t";
  }

  MidTraversal(T->m_pRight);
 }
}

int main()
{
 BinaryTreeNode* T=NULL;

 AddTree(&T, 10);
 AddTree(&T, 12);
 AddTree(&T, 5);
 AddTree(&T, 7);
 AddTree(&T, 4);

 cout<<"Mid reversal tree is:\n";
 MidTraversal(T);

 vector<int> path;
 int sum=0;
 FindPath(T, 22, path, sum);

 return 0;
}

posted on 2010-08-11 14:25  山径山精  阅读(254)  评论(0编辑  收藏  举报

导航