在二元樹中找出和爲某一值的所有路徑(4)

題目:輸入一個整數和一棵二元樹。
從樹的根結點開始往下訪問一直到葉結點所經過的所有結點形成一條路徑。
打印出和與輸入整數相等的所有路徑。
例如 輸入整數22和如下二元樹
  10 
  / \  
 5  12  
 /   \  
4     7
則打印出兩條路徑:10, 12和10, 5, 7。

二元樹節點的數據結構定義爲:
struct BinaryTreeNode // a node in the binary tree
{
int m_nValue; // value of node
BinaryTreeNode *m_pLeft; // left child of node
BinaryTreeNode *m_pRight; // right child of node
};

 

 

 

/*
  Name: 
  Copyright: 
  Author: 
  Date: 22-06-11 09:47
  Description: 輸入一個整數和一棵二元樹。
從樹的根結點開始往下訪問一直到葉結點所經過的所有結點形成一條路徑。
打印出和與輸入整數相等的所有路徑。
例如輸入整數22 和如下二元樹
          10
        / \
       5  12
      / \
     4   7
則打印出兩條路徑:10, 12 和10, 5, 7。
*/
#include<iostream>
#include<iomanip>
using namespace std;

struct BinaryTreeNode // a node in the binary tree
{
int m_nValue; // value of node
BinaryTreeNode *m_pLeft; // left child of node
BinaryTreeNode *m_pRight; // right child of node
};
int a[100];
void cfun(BinaryTreeNode * tp,int z,int t)
//最上面爲 0 層 ; 從零層開始 
//z爲給定的整數值 ,t表示遞歸調用的次數-1,m_nValue 可正可負 
{
     if(tp==NULL)
     {
        if(z==0)
        {
           for(int i=0;i<t;i++)
           cout<<a[i]<<' ';
        }
        return;
     }
    a[t]=tp->m_nValue;
    cfun(tp->m_pLeft,z-tp->m_nValue,t+1);
    cfun(tp->m_pRight,z-tp->m_nValue,t+1); 
}
int main()
{
 
    system("pause");
    return 0;
    }


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章