难度:Easy
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
示例 :给定二叉树1/ \2 3/ \4 5返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。注意:两结点之间的路径长度是以它们之间边的数目表示。
直观方法:最大直径是左子树深度和右子树深度之和,与其孩子最大直径比较的最大值。
/*** 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 {int depth(TreeNode* root){if(!root) return 0;return 1+max(depth(root->left), depth(root->right));}public:int diameterOfBinaryTree(TreeNode* root) {if(!root || (!root->left && !root->right)) return 0;//cout<<depth(root->left)<< "+" <<depth(root->right)<<endl;int res=depth(root->left) +depth(root->right);res=max(res,diameterOfBinaryTree(root->right));res=max(res,diameterOfBinaryTree(root->left));return res;}};
执行用时 :84 ms, 在所有 C++ 提交中击败了6.16%的用户 内存消耗 :35.5 MB, 在所有 C++ 提交中击败了5.39%的用户
效率较低。另一种方法是找出某个根节点,该根节点的左右子树高度之和即为所求。 使用深度优先搜索。
class Solution{public:int diameterOfBinaryTree(TreeNode* root){int distance = 0;dfs(root, distance);return distance;}/*** distance 记录以root为根的子树的最大直径,返回树的高度*/int dfs(TreeNode *root, int &distance){if (root == nullptr)return 0;int left = dfs(root->left, distance);int right = dfs(root->right, distance);distance = max(left + right, distance);return max(left, right) + 1;}};
执行用时 :20 ms, 在所有 C++ 提交中击败了67.87%的用户 内存消耗 :19.6 MB, 在所有 C++ 提交中击败了89.71%的用户