543Diameter of Binary Tree

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.

题目大意

给出一颗二叉树,求叶节点之间的最大距离。

思路

求叶节点的最大距离,可能这个最大的距离并不通过根节点,最大距离为左子树深度与右子树深度之和再加一。所以只需求每个节点的左右子树最大深度即可,边求边得出最大值。

代码

/**
 * 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;
    int diameterOfBinaryTree(TreeNode* root) {
        ans=1;
        depth(root);
        return ans-1;    
    }
    int depth(TreeNode* root)
    {
        if(!root)
            return 0;
        int L=depth(root->left);
        int R=depth(root->right);
        ans=max(ans,L+R+1);
        return max(L,R)+1;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36718317/article/details/86552227