C語言實現(xiàn)找出二叉樹中某個值的所有路徑的方法
更新時間:2014年09月16日 16:25:48 投稿:shichen2014
這篇文章主要介紹了C語言實現(xiàn)找出二叉樹中某個值的所有路徑的方法,針對數(shù)據(jù)結(jié)構(gòu)中二叉樹的實用操作技巧,需要的朋友可以參考下
本文實例講述了C語言實現(xiàn)找出二叉樹中某個值的所有路徑的方法,是非常常用的一個實用算法技巧。分享給大家供大家參考。
具體實現(xiàn)方法如下:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
vector<int> result;
struct Node {
Node(int i = 0, Node *pl = NULL, Node *pr = NULL) : data(i), left(pl), right(pr) {}
int data;
Node *left;
Node *right;
};
Node* Construct()
{
Node *node4 = new Node(7);
Node *node3 = new Node(4);
Node *node2 = new Node(12);
Node *node1 = new Node(5, node3, node4);
Node *root = new Node(10, node1, node2);
return root;
}
void print()
{
copy(result.begin(), result.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
void PrintSum(Node *root, int sum)
{
if(root == NULL)
return;
result.push_back(root->data);
if(root->left == NULL && root->right == NULL && root->data == sum) {
print();
}
PrintSum(root->left, sum - root->data);
PrintSum(root->right, sum - root->data);
result.pop_back();
}
void main()
{
Node *root = Construct();
PrintSum(root, 22);
}
感興趣的朋友可以測試運行一下本文實例。相信本文所述算法對大家C程序算法設(shè)計的學(xué)習(xí)有一定的借鑒價值。
相關(guān)文章
Qt使用SqlLite實現(xiàn)權(quán)限管理的示例代碼
本文主要介紹了Qt使用SqlLite實現(xiàn)權(quán)限管理的示例代碼,管理員針對不同人員進行權(quán)限設(shè)定,具有一定的參考價值,感興趣的可以了解一下2023-09-09
Cocos2d-x UI開發(fā)之CCControlColourPicker控件類使用實例
這篇文章主要介紹了Cocos2d-x UI開發(fā)之CCControlColourPicker控件類使用實例,本文代碼中包含大量注釋來講解CCControlColourPicker控件類的使用,需要的朋友可以參考下2014-09-09
基于OpenCV自定義色條實現(xiàn)灰度圖上色功能代碼
今天通過本文給大家分享基于OpenCV自定義色條實現(xiàn)灰度圖上色功能代碼,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-11-11
opencv配置的完整步驟(win10+VS2015+OpenCV3.1.0)
OpenCV是計算機視覺中經(jīng)典的專用庫,其支持多語言、跨平臺,功能強大,這篇文章主要給大家介紹了關(guān)于opencv配置(win10+VS2015+OpenCV3.1.0)的相關(guān)資料,需要的朋友可以參考下2021-06-06

