题意:求树上任意两节点的最长路径。
分析:最长路径一定经过某个子树的根结点,显然,最长路径的两端要么是该根结点要么是叶子结点,因此,最长路径的长度一定为该子树的左子树高+右子树高。
/** * 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 ans = 0; int maxDepth(TreeNode* root){ if(root == NULL) return 0; int leftdepth = maxDepth(root -> left); int rightdepth = maxDepth(root -> right); ans = max(ans, leftdepth + rightdepth); return max(leftdepth, rightdepth) + 1; } int diameterOfBinaryTree(TreeNode* root) { maxDepth(root); return ans; } };