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; }
相关文章推荐
- Data Structure Binary Tree: Print ancestors of a given binary tree node without recursion
- Data Structure Binary Tree: Boundary Traversal of binary tree
- Data Structure Binary Tree: Largest Independent Set Problem
- LeetCode - 543 - Diameter of Binary Tree
- LeetCode OJ 543 Diameter of Binary Tree [Easy]
- leetcode-504-Diameter of Binary Tree
- Data Structure Binary Tree: Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- LeetCode Diameter of Binary Tree
- dataStructure@ Binary Search Tree
- LeetCode.543 Diameter of Binary Tree
- Diameter of Binary Tree
- Data Structure Binary Tree: Iterative Postorder Traversal
- Diameter of Binary tree
- leetcode(543):Diameter of Binary Tree
- The diameter of a binary tree [No. 40]
- LeetCode 543: Diameter of Binary Tree
- Data Structure Binary Search Tree: Find k-th smallest element in BST (Order Statistics in BST)
- LeetCode@543_Diameter_of_Binary_Tree
- Diameter of Binary Tree
- Diameter of Binary Tree