问题描述:
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.
解题思路:
一定要读清题干!理解题意!
一定要读清题干!理解题意!
一定要读清题干!理解题意!
题目中,树的直径的定义是:树中两个节点最长路径的长度
路径的长度的定义是:两节点之间边的条数。
首先考虑这个路径可能出现在怎样的情况下:
1.叶子结点到根节点的情况
2.两个叶子结点之间(这两个叶子结点可能在某棵子树中)
接下来我们遍历树:
遍历树时,我们返回根节点到叶子结点的长度。
然后我们计算在这棵子树中最长的距离 : max(mx, l + r)
并将最大值存储在mx中。
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int diameterOfBinaryTree(TreeNode* root) { if(!root) return 0; int mx = 0; traverse(root, mx); return mx; } int traverse(TreeNode* root, int& mx){ int ret = 0; if(!root) return 0; int l = root->left ? traverse(root->left, mx) + 1 : 0; int r = root->right ? traverse(root->right, mx) + 1: 0; mx = max(l+r, mx); return max(l, r); } };