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

来源:互联网 发布:萧何月下追韩信淘宝 编辑:程序博客网 时间:2024/06/08 03:09
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如输入整数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

};

分析:首先明白题意,就是让我们求出所有满足要求的路径,路径上所有节点的值的和为我们输入的值。

代码实现:

#include<iostream>#include<vector>#include<string>using namespace std;struct TreeNode{int value;struct TreeNode *left;struct TreeNode *right;};vector<int> path;int x;void addTreeNode(struct TreeNode *&pCurrent,int value)//创建二叉排序树{struct TreeNode *temp;if(pCurrent==NULL){temp=new TreeNode();temp->value=value;temp->left=NULL;temp->right=NULL;pCurrent=temp;return ;}if(pCurrent->value>value){addTreeNode(pCurrent->left,value);return ;}if(pCurrent->value<value){addTreeNode(pCurrent->right,value);return ;}cout<<"Node repted!!!"<<endl;}void printPath(){for(vector<int>::iterator iter=path.begin(); iter!=path.end();iter++){cout<<*iter<<" ";}cout<<endl;}void helper(struct TreeNode *pCurrent, int sum){if(pCurrent==NULL) return ;if(pCurrent->left==NULL&&pCurrent->right==NULL&&(sum+pCurrent->value)==x){path.push_back(pCurrent->value);printPath();path.pop_back();return ;}if(pCurrent->left!=NULL){path.push_back(pCurrent->value);helper(pCurrent->left,sum+pCurrent->value);path.pop_back();}if(pCurrent->right!=NULL){path.push_back(pCurrent->value);helper(pCurrent->right,sum+pCurrent->value);path.pop_back();}}void inOrderTree(struct TreeNode *pCurrent)//中序遍历,测试用的{if(pCurrent==NULL) return ;if(pCurrent->left!=NULL)inOrderTree(pCurrent->left);cout<<pCurrent->value<<" ";if(pCurrent->right!=NULL)inOrderTree(pCurrent->right);}int main(){struct TreeNode *root=NULL;addTreeNode(root,10);addTreeNode(root,12);addTreeNode(root,5);addTreeNode(root,4);addTreeNode(root,7);//inOrderTree(root);//cout<<endl;scanf("%d",&x);helper(root,0);return 0;}


0 0
原创粉丝点击