找出二叉树中和为某一定值的所有路径
来源:互联网 发布:天下三捏脸数据 编辑:程序博客网 时间:2024/04/25 18:12
题目如题所示,思路如下:
用前序遍历的方式访问到某一节点时,我们把该节点添加到路径上,并累加该节点的值。
如果该节点为叶子节点且路径中节点的值刚好等于输入的定值,则当前路径符合要求,
我们把这条路径打印出来。如果当前节点不满足条件,则访问他的子结点。当前节点
访问结束之后,递归函数将自动返回到它的父亲节点。
代码如下:
#include <stdlib.h>#include <stdio.h>typedef struct BiTree{ int data; struct BiTree *lchild; struct BiTree *rchild; }BiTree;BiTree* createTree(BiTree *root){ int temp; scanf("%d",&temp); if (temp!=-1) { root = (BiTree*)malloc(sizeof(BiTree)); root->data = temp; root->lchild = createTree(root->lchild); root->rchild = createTree(root->rchild); } return root;}void preOrder(BiTree *root){ if (root) { printf("%d ",root->data); preOrder(root->lchild); preOrder(root->rchild); }}int getDepth(BiTree *root){ if (root==NULL) { return 0; } int lDepth = getDepth(root->lchild); int rDepth = getDepth(root->rchild); return (lDepth>rDepth)?lDepth+1:rDepth+1;}int isLeaf(BiTree *root){ if (root) { if (root->lchild==NULL&&root->rchild==NULL) { return 1; } } return 0;}void findPath(BiTree *root, int expSum, int *count, int stack[], int *top, int curSum){ if (root==NULL) { return ; } stack[++(*top)] = root->data; curSum += root->data; if (curSum == expSum && isLeaf(root)) { (*count)++; printf("Found %d path: ",*count); for (int i=0; i<=(*top); i++) { printf("%d ",stack[i]); } printf("\n"); } if (root->lchild) { findPath(root->lchild, expSum, count, stack, top, curSum); } if (root->rchild) { findPath(root->rchild, expSum, count, stack, top, curSum); } (*top)--;}int main(int argc, const char * argv[]){ //测试用例:10 5 4 -1 -1 7 -1 -1 12 -1 -1 BiTree *root = NULL; root = createTree(root); preOrder(root); printf("\nThe depth is %d.\n",getDepth(root)); int expSum = 22; int curSum = 0; int count = 0; int stack[50]; int top=-1; findPath(root, expSum, &count, stack, &top, curSum); if (count==0) { printf("No path!\n"); } return 1;}
0 0
- 找出二叉树中和为某一定值的所有路径
- 二叉树中和为某一定值的路径
- 找出二元树中和为某一值的所有路径
- 二叉树中和为某一值的所有路径
- 找出二叉树中和为某值的所有路径
- 微软面试100题系列---在二叉树中找出和为某一定值的所有路径
- 【July第4题】寻找二叉树中和为某一定值的路径
- 【IT笔试面试题整理】二叉树中和为某一值的路径--所有可能路径
- 面试题04 - 二叉树中和为某一值的所有路径 [树]
- [程序员面试题精选100题]4.二叉树中和为某一值的所有路径
- 剑指offer面试题之二叉树中和为某一值的所有路径
- 剑指offer:二叉树中和为某一值的所有路径(java)
- 寻找树中和为定值的所有路径
- 二元树中和为某一值的所有路径
- 二元树中和为某一值的所有路径[数据结构]
- 二元树中和为某一值的所有路径
- 二元树中和为某一值的所有路径
- 二元树中和为某一值的所有路径[数据结构]
- OpenCV基础篇之使用CMake管理工程
- 字典树sdutoj 1500模板
- XDOJ1180 - 对称数
- OpenCV基础篇之查找表
- 图像二值化
- 找出二叉树中和为某一定值的所有路径
- docker学习 主流的pass平台(体验的是设计模式)
- @Override错误
- VS 自带打包程序
- CentOS上编译安装OpenCV-2.3.1与ffmpeg-2.1.2
- UVa 11752 - The Super Powers (数论)
- Developing IOS 7 Apps for iPhone and iPad (Lecture 10)
- 最大乘积(Maximum Product,UVA 11059)
- java制作五子棋和象棋之二象棋图形界面的设计