题目描述:
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.
求树中的最长路径长度,路径的定义为任意两个连通的节点之间的通路。
由于不一定经过根结点,所以从根结点递归的时候需要分经过根结节点和不经过根结点两种情况计算,同时如果经过根结点,那么为了求最长路径就需要求左子树的高度和右子树的高度,求树的高度也可以通过递归实现。
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
if (root==NULL||(root->left==NULL&&root->right==NULL)) return 0;
int diameter=0;
diameter=max(diameterOfBinaryTree(root->left),diameterOfBinaryTree(root->right));
if(root->left==NULL||root->right==NULL)
diameter=max(diameter,height_from_cur(root->left)+height_from_cur(root->right)+1);
else diameter=max(diameter,height_from_cur(root->left)+height_from_cur(root->right)+2);
return diameter;
}
int height_from_cur(TreeNode* cur){
if (cur==NULL||(cur->left==NULL&&cur->right==NULL)) return 0;
return max(height_from_cur(cur->left),height_from_cur(cur->right))+1;
}
};
本文介绍了一种计算二叉树中最长路径长度的算法。该算法采用递归方式,考虑了路径是否经过根节点的情况,并通过计算左右子树高度来确定最长路径。
434

被折叠的 条评论
为什么被折叠?



