[编程之美:3.8]求二叉树中节点的最大距离
2010-09-12 11:02
423 查看
如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,我们姑且定义"距离"为两节点之间边的个数。写一个程序求一棵二叉树中相距最远的两个节点之间的距离。
//============================================================================ // Name : maxLenInBtree.cpp // Author : qibaoyuan // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <cassert> using namespace std; struct LTNOde { int nMaxLeft;//左子数的最大距离 int nMaxRight;//右子数的最大距离 LTNOde *lChild; LTNOde *rChild; int data; LTNOde() { nMaxRight = 0; nMaxLeft = 0; lChild = NULL; rChild = NULL; } LTNOde(int data) { nMaxRight = 0; nMaxLeft = 0; lChild = NULL; rChild = NULL; } }; //创建一个拥有nNode个节点的完全二叉数 LTNOde *createLBiTree(int nNode) { LTNOde *root = new LTNOde[nNode]; assert(root); #define root(i) &root[i-1]; int i; LTNOde *tNodePtr; for (i = 0; i < nNode; i++) { tNodePtr = root(i); tNodePtr->data = i; } for (i = 1; i <= nNode; i++) { int j = 2 * i;//left child if (j > nNode) break; tNodePtr = root(i); tNodePtr->lChild = root(j); if (j < nNode) tNodePtr->rChild = root(j+1); } return root; } void findMaxLen(LTNOde *rt, int& nMaxLen) { if (!rt) return;//递归出口 if (!rt->lChild) rt->nMaxLeft = 0; else { findMaxLen(rt->lChild, nMaxLen); rt->nMaxLeft = rt->lChild->nMaxLeft >= rt->lChild->nMaxRight ? rt->lChild->nMaxLeft + 1 : rt->lChild->nMaxRight + 1; } if (!rt->rChild) rt->nMaxRight = 0; else { findMaxLen(rt->rChild, nMaxLen); rt->nMaxRight = rt->rChild->nMaxLeft >= rt->rChild->nMaxRight ? rt->rChild->nMaxLeft + 1 : rt->rChild->nMaxRight + 1; } if (rt->nMaxLeft + rt->nMaxRight > nMaxLen) nMaxLen = rt->nMaxLeft + rt->nMaxRight; } int main() { int const nNode = 3; LTNOde *biTree = createLBiTree(nNode); int nMaxLen = 0; findMaxLen(biTree, nMaxLen); cout << nMaxLen << endl; //delete[] biTree; return 0; }
相关文章推荐
- 编程之美3.8:求二叉树节点的最大距离
- 《编程之美》读书笔记12: 3.8 求二叉树中节点的最大距离
- 二叉树中节点的最大的距离(编程之美3.8)
- 《编程之美》读书笔记12: 3.8 求二叉树中节点的最大距离
- 《编程之美》读书笔记12: 3.8 求二叉树中节点的最大距离
- [编程之美3.8]求二叉树节点的最大距离
- 二叉树中节点的最大的距离(编程之美3.8)
- 编程之美3.8 求二叉树中节点的最大距离
- 二叉树中节点的最大的距离(编程之美3.8)
- 《编程之美》 3.8 求二叉树中节点的最大距离
- 编程之美3.8 求二叉树中节点的最大距离
- 编程之美:求二叉树中节点的最大距离(非递归法)
- 《编程之美: 求二叉树中节点的最大距离》的另一个解法
- 编程之美之求二叉树中节点的最大距离
- 编程之美 3.8 求二叉树中节点的最大距离 3.9 重建二叉树
- 编程之美读书笔记_3.8 求二叉树中节点的最大距离 和 3.10分层遍历二叉树 相关代码
- 《编程之美: 求二叉树中节点的最大距离》的另一个解法
- 编程之美------3.8 求二叉树中节点的最大距离
- 编程之美3.8: 求二叉树中节点的最大距离
- 《编程之美: 求二叉树中节点的最大距离》的另一个解法