题目描述
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
示例
1/ \2 3/ \4 5返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
解题思路
解法1,计算穿过root,root的左孩子,root的右孩子的直径比较
/*** 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 calc_depth(TreeNode* root, int count) {if (root == NULL)return count-1;return max(calc_depth(root->left, count+1), calc_depth(root->right, count+1));}int diameterOfBinaryTree(TreeNode* root) {if (root==NULL)return 0;int depth_root = calc_depth(root->left, 1) + calc_depth(root->right, 1);int depth_left = diameterOfBinaryTree(root->left);int depth_right = diameterOfBinaryTree(root->right);return max(depth_root, max(depth_left, depth_right));}};
解法2,在计算depth的过程中便开始记录
/*** 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 res=0;int calc_depth(TreeNode* root, int count) {if (root == NULL)return 0;int l = calc_depth(root->left, count+1);int r = calc_depth(root->right, count+1);res = max(res, l+r+1);return max(l, r)+1;}int diameterOfBinaryTree(TreeNode* root) {if (root==NULL)return 0;calc_depth(root, 1);return res-1;}};
