题目:
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1 / \ 2 3 / \ 4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
翻译:
给定一棵二叉树,你需要计算这棵树直径的长度。二叉树的直径是树中任意两个节点之间的最长路径的长度。这个路径可以经过或者不经过根节点。
例子:
给定一棵二叉树
Given a binary tree
1 / \ 2 3 / \ 4 5
返回 3 , 长度对应的路径为 [4,2,1,3] 或 [5,2,1,3]。
注意:两个节点之间的路径长度由它们之间的边的个数表示。
思路:
首先我们假设树的直径是经过根节点root的,那么只要通过递归计算root的最深左子树和最深右子树的深度相加求和即为所求,但是题目要求这个树的直径可以不经过根节点root,那么我们先用递归的方法依次求得,diameterOfBinary(root->left),diameterOfBinary(root->right),然后取root,root->left,root->right三者中最大的一个作为树的直径返回即可。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int deep(TreeNode* node) {
int res = 0;
if (node != NULL) {
res++;
res += max(deep(node->left), deep(node->right));
}
return res;
}
int diameterOfBinaryTree(TreeNode* root) {
if (root == NULL) {
return 0;
}
int result=deep(root->left) + deep(root->right);
return max(result, max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right)));
}
};
int main()
{
Solution s;
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
int result=s.diameterOfBinaryTree(root);
cout << result << endl;
return 0;
}