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.
题目内容: 题目给出一个二叉树,让我们求出这个二叉树中任意两点之间的最长路径长度。例如,题目给出的二叉树,最长的路径是从4到3,或者是5到3,他们的路径都是3。
解题思路: 因为最长路径所经过的点都能构成一个新的二叉树,那么我们遍历每一个点,假设这个点是最长路径的点构成的二叉树的根节点,那么我们就分别求出以这个点为根节点的二叉树的左子树和右子树的高度之和,就是以这个点为根节点的二叉树的最长路径。也就说,我们可以遍历所有点,分别计算这个点的左子树和右子树的高度,然后相加,得到的最大值就是题目要求的结果。 那么如何计算左(右)子树的高度呢?可以看到每个左(右)子树的高度又依赖于左(右)子树的左(右)子树,所以我们可以采用递归的算法,递归计算左(右)子树的高度,当一个节点的左(右)子树的高度都已经计算好了,那么把左(右)子树的高度相加,再与目前的最长路径长度比较,保留最大值。
代码:
// // main.cpp // 543. Diameter of Binary Tree // // Created by mingjc on 2017/4/9. // Copyright © 2017年 mingjc. All rights reserved. // #include <iostream> #include <unordered_set> using namespace std; #define max(a, b) (a > b ? a : b) /** * 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 maxDiameter = 0; int diameterOfBinaryTree(TreeNode* root) { maxChild(root); return maxDiameter; } int maxChild(TreeNode* node) { if (node == NULL) return 0; int left = maxChild(node->left); int right = maxChild(node->right); maxDiameter = max(left + right + 1, maxDiameter); return max(left, right) + 1; } }; int main(int argc, const char * argv[]) { Solution sln; cout << sln.diameterOfBinaryTree(new TreeNode(1)) << endl; return 0; }