4.在二元树中找出和为某一值的所有路径
来源:互联网 发布:手机看病软件 编辑:程序博客网 时间:2024/06/01 11:45
题目:输入一个整数和一棵二元树。
打印出和与输入整数相等的所有路径。
例如 输入整数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
};
分析:
该题就是判断一条路径value和是否等于给定值,用DFS
程序代码:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef struct node
- {
- int value;
- struct node*lchild,*rchild;
- }BTNode;
- #define N 22
- int a[10]; //a数组存放路径
- BTNode* CreateTree(BTNode *L);
- void Fun(BTNode *L,int count,int index);
- int main()
- {
- int count=0,index=0; //count为value和,index为存储在a数组中的元素个数
- BTNode *L=NULL;
- L=CreateTree(L,count,index);
- Fun(L,count,index); //关键函数
- return 0;
- }
- BTNode *CreateTree(BTNode *L)
- {
- BTNode *s=NULL,*cur=NULL;
- L=(BTNode *)malloc(sizeof(BTNode));
- L->value=10;
- cur=L;
- s=(BTNode *)malloc(sizeof(BTNode));
- s->value=5;
- cur->lchild=s;
- cur=s;
- s=(BTNode *)malloc(sizeof(BTNode));
- s->value=4;
- s->lchild=s->rchild=NULL;
- cur->lchild=s;
- s=(BTNode *)malloc(sizeof(BTNode));
- s->value=7;
- s->lchild=s->rchild=NULL;
- cur->rchild=s;
- cur=L;
- s=(BTNode *)malloc(sizeof(BTNode));
- s->value=12;
- s->lchild=s->rchild=NULL;
- cur->rchild=s;
- return L;
- }
- void Fun(BTNode *L,int count,int index)
- {
- int i;
- if (L)
- {
- count+=L->value;
- a[index++]=L->value;
- if (L->lchild==NULL&&L->rchild==NULL)
- {
- if (count==N)
- {
- for (i=0;i<index;i++)
- {
- printf("%d ",a[i]);
- }
- printf("\n");
- }
- }
- else
- {
- Fun(L->lchild,count,index);
- Fun(L->rchild,count,index);
- }
- }
- }
- 4.在二元树中找出和为某一值的所有路径(树)
- 4.在二元树中找出和为某一值的所有路径(树)
- 4.在二元树中找出和为某一值的所有路径(树)
- 4.在二元树中找出和为某一值的所有路径(树)
- 4.在二元树中找出和为某一值的所有路径
- 4.在二元树中找出和为某一值的所有路径
- 面试100题:4.在二元树中找出和为某一值的所有路径
- 4.在二元树中找出和为某一值的所有路径
- 面试100题:4.在二元树中找出和为某一值的所有路径
- 4.在二元树中找出和为某一值的所有路径
- 在二元树中找出和为某一值的所有路径的个人代码
- 在二元树中找出和为某一值的所有路径(树)
- 在二元树中找出和为某一值的所有路径(树)
- No4、在二元树中找出和为某一值的所有路径(树)
- 在二元树中找出和为某一值的所有路径(树)
- 在二元树中找出和为某一值的所有路径(树)
- 在二元树中找出和为某一值的所有路径-递归算法
- 在二元树中找出和为某一值的所有路径
- 常用js验证
- Oracle经验集锦
- 打开,关闭窗口代码
- 2011年 C++程序设计
- 怎样提高软件技术:从新手到入门的一些思考
- 4.在二元树中找出和为某一值的所有路径
- 一些关于Launcher的文章
- 程序员发展:机会远比钱重要
- 跟我一起写 Makefile(六)
- 2011年 C++程序设计
- Fix: 'Unable to load one or more of the requested types' Errors
- 如果控制pop弹出的页面层数
- 删除结尾字符串
- linux 信号量