您的位置:首页 > 其它

Data Structure Binary Tree: Diameter of a Binary Tree

2014-03-27 12:12 615 查看
http://www.geeksforgeeks.org/diameter-of-a-binary-tree/

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;

struct node {
int data;
struct node *left, *right;
node() : data(0), left(NULL), right(NULL) { }
node(int d) : data(d), left(NULL), right(NULL) { }
};

void print(node *node) {
if (!node) return;
print(node->left);
cout << node->data << " ";
print(node->right);
}

int diameter(node *root, int &ans) {
if (!root) return 0;
int l = diameter(root->left, ans);
int r = diameter(root->right, ans);
ans = max(ans, l+r+1);
return max(l, r) + 1;
}

int main() {
struct node* root = new node(1);
root->left = new node(2);
root->right = new node(3);
root->left->left = new node(4);
root->left->right = new node(5);
int ans = 0;
diameter(root, ans);
cout << ans << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: