编程之美 求二叉树中节点的最大距离 非递归
2014-03-31 20:36
357 查看
The basic program is to get the height of a binary tree. We could use BFS to realize that. So the result is :
Wrong program!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Pls notice that two leaf nodes and an internal node may have a longer distance, The right code is :
http://blog.csdn.net/taoqick/article/details/21881707
#include <stdio.h> #include <iostream> #include <vector> using namespace std; class TreeNode { public: int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; void display(TreeNode* root, int col = 0) { if(root == 0) return; display(root->right, col + 1); for(int i = 0; i < col; ++i) std::cout<<"| "; cout<<"|"<<root->val<<std::endl; display(root->left, col + 1); } int getHeight(TreeNode* root) { int cnt = 0, i, j, cur = 0, next = 1; vector<TreeNode*> layers[2]; layers[cur].push_back(root); while (!layers[cur].empty()) { ++cnt; for (i = 0; i < layers[cur].size(); ++i) { if (layers[cur][i]->left) layers[next].push_back(layers[cur][i]->left); if (layers[cur][i]->right) layers[next].push_back(layers[cur][i]->right); } layers[cur].clear(); cur = !cur; next = !next; } return cnt; } int getMaxDistance(TreeNode* root) { int lcount = 0, rcount = 0, res = 0; if (root == NULL) return 0; while (root->left && !root->right || !root->left && root->right) { ++res; if (root->left) root = root->left; else root = root->right; } if (root->left && root->right) { lcount = getHeight(root->left); rcount = getHeight(root->right); } return res + lcount + rcount; } int main() { TreeNode *root = new TreeNode(0); root->left = new TreeNode(1); root->right = new TreeNode(2); root->left->left = new TreeNode(3); root->left->right = new TreeNode(4); root->right->left = new TreeNode(5); root->right->right = new TreeNode(6); root->right->right->right = new TreeNode(7); display(root); int res = getMaxDistance(root); return 0; }
Wrong program!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Pls notice that two leaf nodes and an internal node may have a longer distance, The right code is :
http://blog.csdn.net/taoqick/article/details/21881707
相关文章推荐
- MATLAB中contour函数用法
- C# 静态类、静态构造器、静态方法、静态字段
- [学习笔记]小型java游戏引擎_1
- PHP随笔(继承)
- Eclipse常用快捷键
- Java性能优化系列之三--并发程序设计详解
- 004_018 Python 添加 修改一系列已经命名的参数 用于搜集一系列元素,然后重命名
- C++与VB 异同(一)
- java学习总结——第八天
- 多项式加法(单链表 c语言)
- struts2区分get/post请求
- Java性能优化系列之二--程序优化
- 本文介绍Google Native Client的设计思路.
- C++编程 - 回字有四样写法,你知道么?
- Java代码质量检测评估工具
- Eclipse下切换项目的svn地址
- JavaWeb(李兴华著)开发笔记
- Java性能优化系列之一--设计优化
- ThinkPHP“学习”之路
- Java和.net对比分析