題目:
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 ans = 0;
int dfs(TreeNode* node) {
if (!node) return 0;
int left = dfs(node->left);
int right = dfs(node->right);
ans = max(ans, left + right);
return 1 + max(left, right);
}
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return ans;
}
};