二叉樹中和為某一值的路徑——25

來源:互聯網
上載者:User

標籤:include   程式設計   二叉樹   葉子   

    輸入一個二叉樹和一個整數,列印出二叉樹中結點值的和為輸入整數的所有路徑。從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。

650) this.width=650;" src="http://s2.51cto.com/wyfs02/M00/80/EF/wKiom1dFDnWQdxTiAAALYrM1qGA376.png" title="二叉樹another.png" alt="wKiom1dFDnWQdxTiAAALYrM1qGA376.png" />

    如的二叉樹,當輸入根結點和一個數值12的時候,就有兩條路徑“1->2->4->5”和“1->3->8”,如果存在,就輸出上述路徑,如果沒有任何一條路徑滿足就不輸出路徑並提示;

    首先,路徑一定是從根結點開始到某個葉子結點結束,這才是一條路徑,因此,應該最先訪問的就是根結點,而在二叉樹的先中後序遍曆中只有先序遍曆是最先訪根結點的,所以可以用如下方法:用先序遍曆方法遍曆二叉樹,每當經過一個結點的時候就將其值進行儲存相加,如果中途發現或者到達葉子結點之後,當前路徑相加得到的值並不滿足要求的值,則往回退並將值減去,或者當前路徑已經滿足,則需要再去換一條路徑訪問看是否還有其他路徑滿足條件,而能夠提供往回退的方法就只有遞迴了,直至遍曆完畢二叉樹;


程式設計如下:

#include <iostream>#include <assert.h>#include <vector>using namespace std;struct BinaryTreeNode//二叉樹結點資料結構{    int _val;    BinaryTreeNode *_Lnode;    BinaryTreeNode *_Rnode;    BinaryTreeNode(int val)        :_val(val)         ,_Lnode(NULL)         ,_Rnode(NULL)    {}};BinaryTreeNode* _Create(int *arr, size_t& index, size_t size)//建立二叉樹{    if((index < size) && (arr[index] != ‘#‘))    {        BinaryTreeNode *root = new BinaryTreeNode(arr[index]);        root->_Lnode = _Create(arr, ++index, size);        root->_Rnode = _Create(arr, ++index, size);        return root;    }    else        return NULL;}BinaryTreeNode* CreateBinaryTree(int *arr, size_t size){    assert(arr && size);    size_t index = 0;    return _Create(arr, index, size);}void DestoryBinaryTree(BinaryTreeNode *root)//銷毀二叉樹{    if(root != NULL)    {        DestoryBinaryTree(root->_Lnode);        DestoryBinaryTree(root->_Rnode);        delete root;    }}void PrevOrder(BinaryTreeNode *root)//前序走訪列印出二叉樹{    if(root != NULL)    {        cout<<root->_val<<" ";        PrevOrder(root->_Lnode);        PrevOrder(root->_Rnode);    }}void _Count(BinaryTreeNode* root, vector<int> *pv, int& count, int num){    if(root != NULL)    {        count += root->_val;//每當一個結點不為NULL的時候,就將其放入容器中且加上其值        (*pv).push_back(root->_val);        _Count(root->_Lnode, pv, count, num);        _Count(root->_Rnode, pv, count, num);        if(count == num)//當找到一個路徑的時候就將其列印出來        {            cout<<"A Path Is : ";            for(size_t i = 0; i < (*pv).size(); ++i)                cout<<(*pv)[i]<<"->";            cout<<"NULL"<<endl;        }        count -= (*pv).back();//退回上一步        (*pv).pop_back();    }}void PrintPathOfNumInBT(BinaryTreeNode *root, int num)//列印路徑{    assert(root);    vector<int> v;//用一個容器來存放路徑    int count = 0;//用一個計數器計算和    _Count(root, &v, count, num);}int main(){    int arr[] = {1,2,6,‘#‘,‘#‘,4,5,‘#‘,‘#‘,‘#‘,3,7,‘#‘,‘#‘,8,‘#‘,‘#‘};    int num = 12;    BinaryTreeNode *root = CreateBinaryTree(arr, sizeof(arr)/sizeof(arr[0]));    cout<<"PrevOrder:";    PrevOrder(root);    cout<<endl;    PrintPathOfNumInBT(root, num);    DestoryBinaryTree(root);    return 0;}


運行程式:

650) this.width=650;" src="http://s5.51cto.com/wyfs02/M02/81/FC/wKioL1dGuqvgoxDNAAAIPHY3A4A100.png" title="PrintPath.png" alt="wKioL1dGuqvgoxDNAAAIPHY3A4A100.png" />



《完》

本文出自 “敲完代碼好睡覺zzz” 部落格,請務必保留此出處http://2627lounuo.blog.51cto.com/10696599/1783531

二叉樹中和為某一值的路徑——25

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.