在二元树中找出和为某一值的所有路径
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数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
};
解析:
建树依然建立二元查找树,然后用深搜,用一个path数组把结点的值存储起来。用深搜打印路径比较方便。没有什么特殊和很难的地方。
这里需要注意的是:这个系列中我在系列(一)中上传的pdf文件里题目4的图形没对,可能会有误导。树的形状应该是
10
/ \
5 12
/ \
4 7
最后,依然贴代码吧!
- /*
- * Problem_4.cpp
- * 在二元树中找出和为某一值的所有路径
- * Created on: 2012-8-28
- * Author: Administrator
- */
- #include<stdio.h>
- struct BinaryTreeNode{
- int data;
- BinaryTreeNode *pLeft,*pRight;
- BinaryTreeNode(){
- pLeft=pRight=NULL;
- }
- };
- #define M 100
- int path[M],top=-1;
- bool addNode(BinaryTreeNode **root,int value){
- if(*root!=NULL){
- if(value>(*root)->data){
- addNode(&((*root)->pRight),value);
- }else if(value<(*root)->data){
- addNode(&((*root)->pLeft),value);
- }else{
- printf("repeated node!\n");
- return false;
- }
- }else{
- BinaryTreeNode *p;
- p=new BinaryTreeNode();
- p->data=value;
- *root=p;
- }
- return true;
- }
- /*
- *
- * */
- void search(BinaryTreeNode *cur,int sum,int &s){
- path[++top]=cur->data;
- if(cur->pLeft==NULL&&cur->pRight==NULL&&s==sum+cur->data){
- for(int i=0;i<=top;i++){
- printf("%d ",path[i]);
- }
- printf("\n");
- }
- if(sum+cur->data>=s){//剪枝
- --top;
- return;
- }
- if(cur->pLeft!=NULL)
- search(cur->pLeft,sum+cur->data,s);
- if(cur->pRight!=NULL)
- search(cur->pRight,sum+cur->data,s);
- --top;
- }
- int main(){
- int data[5]={10,5,12,4,7};
- BinaryTreeNode *root=NULL;
- for(int i=0;i<5;i++){
- addNode(&root,data[i]);
- }
- int a=22;
- search(root,0,a);
- return 0;
- }