博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
剑指Offer:面试题25
阅读量:4610 次
发布时间:2019-06-09

本文共 2559 字,大约阅读时间需要 8 分钟。

题目描述:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。 九度OJ地址: 自己写的代码,自己运行没问题,提交总是不通过 = =
1 #include
2 #include
3 #include
4 #include
5 #include
6 using namespace std; 7 8 #define MAX 100 9 struct BinaryTreeNode{10 int index;11 int value;12 int lchild;13 int rchild;14 };15 16 BinaryTreeNode p[MAX];17 vector
path;18 19 20 void FindPath(BinaryTreeNode* p,int exceptedNum,vector
path,int currentNum){21 currentNum=currentNum+(p->value);22 path.push_back(*p);23 bool IsLeaf=(p->lchild==-1)&&(p->rchild==-1);24 25 if(currentNum==exceptedNum&&IsLeaf)26 {27 printf("A path is found: ");28 vector
::iterator iter=path.begin();29 for(;iter!=path.end();++iter)30 {31 printf("%d ",iter->index);32 }33 printf("\n");34 }35 if(p->lchild!=-1)36 FindPath(p+(p->lchild-p->index),exceptedNum,path,currentNum);37 if(p->rchild!=-1)38 FindPath(p+(p->rchild-p->index),exceptedNum,path,currentNum);39 currentNum=currentNum-(p->value);40 path.pop_back();41 42 43 }44 void FindPath(BinaryTreeNode* p,int exceptedNum){45 if(p==NULL)46 return;47 int currentNum=0;48 FindPath(p,exceptedNum,path,currentNum);49 50 }51 int main()52 {53 int n,k;54 int v,l,r;55 while(scanf("%d %d",&n,&k)==2)56 {57 memset(p,-1,sizeof(p));58 for(int i=0;i

找了大神代码完美运行:

#include
#include
#include
#include
#include
using namespace std;#define MAX 100struct BinaryTreeNode{ int index; int value; int lchild; int rchild;};BinaryTreeNode p[MAX];vector
path;void FindPath(BinaryTreeNode* p,int exceptedNum,vector
path,int currentNum){ currentNum=currentNum+(p->value); path.push_back(*p); bool IsLeaf=(p->lchild==-1)&&(p->rchild==-1); if(currentNum==exceptedNum&&IsLeaf) { printf("A path is found: "); vector
::iterator iter=path.begin(); for(;iter!=path.end();++iter) { printf("%d ",iter->index); } printf("\n"); } if(p->lchild!=-1) FindPath(p+(p->lchild-p->index),exceptedNum,path,currentNum); if(p->rchild!=-1) FindPath(p+(p->rchild-p->index),exceptedNum,path,currentNum); currentNum=currentNum-(p->value); path.pop_back();}void FindPath(BinaryTreeNode* p,int exceptedNum){ if(p==NULL) return; int currentNum=0; FindPath(p,exceptedNum,path,currentNum);}int main(){ int n,k; int v,l,r; while(scanf("%d %d",&n,&k)==2) { memset(p,-1,sizeof(p)); for(int i=0;i

慢慢学习吧

转载于:https://www.cnblogs.com/sunrunzhi/p/3949768.html

你可能感兴趣的文章
City Upgrades
查看>>
“人少也能办大事”---K2 BPM老客户交流会
查看>>
关于七牛进行图片添加文字水印操作小计
查看>>
DataSource数据库的使用
查看>>
CentOS开启samba实现文件共享
查看>>
MSSQL使用sqlbulkcopy批量插入数据
查看>>
证明一个数能被3整除,当且仅当它的各位数的和能被3整除
查看>>
2018秋寒假作业4—PTA编程总结1
查看>>
android自适应屏幕
查看>>
2019-北航面向对象-电梯作业总结
查看>>
SqlHelper
查看>>
初识算法、数据结构
查看>>
Luogu4069 SDOI2016 游戏 树链剖分、李超线段树
查看>>
Java的内部类真的那么难以理解?
查看>>
一文搞懂Java环境,轻松实现Hello World!
查看>>
hash实现锚点平滑滚动定位
查看>>
也谈智能手机游戏开发中的分辨率自适应问题
查看>>
【转】MYSQL数据库设计规范与原则
查看>>
《中国大历史》—— 读后总结
查看>>
回溯法算法框架
查看>>