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 longestpath 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 depth(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL){
if(root->right==NULL) return 0;
else return 1+ Solution::depth(root->right);
}else{
if(root->right==NULL) return 1+ Solution::depth(root->left);
else return max(Solution::depth(root->left), Solution::depth(root->right))+1;
}
}
int diameterOfBinaryTree(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL && root->right==NULL) return 0;
if(root->left!=NULL && root->right!=NULL) return Solution::depth(root->left) + Solution::depth(root->right)+2;
return Solution::depth(root->left) + Solution::depth(root->right)+1;
}
};
这样没有考虑,最长距离有可能从子树中产生,即不过根节点。
class Solution {
public:
int depth(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL){
if(root->right==NULL) return 0;
else return 1+ Solution::depth(root->right);
}else{
if(root->right==NULL) return 1+ Solution::depth(root->left);
else return max(Solution::depth(root->left), Solution::depth(root->right))+1;
}
}
int diameter(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL && root->right==NULL) return 0;
if(root->left!=NULL && root->right!=NULL) return Solution::depth(root->left) + Solution::depth(root->right)+2;
return Solution::depth(root->left) + Solution::depth(root->right)+1;
}
int diameterOfBinaryTree(TreeNode* root) {
if(root==NULL) return 0;
return max(max(diameter(root),diameterOfBinaryTree(root->left)),diameterOfBinaryTree(root->right));
}
};
改为函数depth测树深,diameter以根结点为中间路径的最大长度,则diameterOfBinaryTree则递归访问以该点为根结点的长度。