求二叉树中节点的最大距离
来源:互联网 发布:淘宝自动充值没到账 编辑:程序博客网 时间:2024/06/14 11:24
如果我们把二叉树看成一个图,
父子节点之间的连线看成是双向的,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,
父子节点之间的连线看成是双向的,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,
求一棵二叉树中相距最远的两个节点之间的距离。
#include "stdlib.h"#include "stdio.h"typedef struct BTNode{int data;struct BTNode *lnode;struct BTNode *rnode;}BTNode;BTNode *CreateTree(int pre[], int in[], int l1, int r1, int l2, int r2){BTNode *s;int i;if(l1 > r1)return NULL;s = (BTNode *)malloc(sizeof(BTNode));s->lnode = s->rnode = NULL;for(i=l2; i<=r2; ++i){if(pre[l1] == in[i]){break;}}s->data = in[i];s->lnode = CreateTree(pre, in, l1+1, l1+i-l2, l2, i-1);s->rnode = CreateTree(pre, in, l1+i-l2+1, r1, i+1, r2);return s;}void PrePrint(BTNode *p){if(p != NULL){printf("%d ", p->data);PrePrint(p->lnode);PrePrint(p->rnode);}}void InPrint(BTNode *p){if(p != NULL){InPrint(p->lnode);printf("%d ", p->data);InPrint(p->rnode);}}void FindDepth(BTNode *p, int depth, int &maxDepth){if(p != NULL){++depth;printf("current depth = %d\n", depth);//if depth bigger than maxDepth;if(depth > maxDepth){maxDepth = depth;}FindDepth(p->lnode, depth, maxDepth);FindDepth(p->rnode, depth, maxDepth);--depth;}}void main(){int pre[] = {10, 5, 4, 7, 12, 8, 11, 6};int in[] = {4, 5, 12, 7, 10, 11, 8, 6};BTNode *p;p = CreateTree(pre, in, 0, 7, 0, 7);int depth = 0;int maxDepth = 0;FindDepth(p, depth, maxDepth);printf("maxDepth = %d\n", maxDepth);}
0 0
- 【二叉树】求二叉树中节点的最大距离
- 求二叉树中节点最大距离
- 3.8求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 11、求二叉树中节点的最大距离...
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中两个节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- python之urllib
- 解决Eclipse里找不到courier new字体选项
- wireshark分析m3u8
- pre小技巧:强制换行与横向滚动条[转]
- 排序:简单排序算法实现:冒泡,选择,插入
- 求二叉树中节点的最大距离
- Hibernate4.1不能读取xml解决方法
- Pearson,Kendall和Spearman三种相关分析方法的异同
- linux redhat静态ip的详细配置
- 27个iOS开发中的小技巧
- 有关于Fragment是否应该有empty constructor的问题
- windows/linux避免多线程应用程序在多核间切换,影响程序效率
- Hibernate 所有缓存机制详解
- iOS 手机号正则表达式(全)