3.10 binary tree diameter

topic

Given a binary tree, you need to calculate the length of its diameter. A binary tree is the maximum length of the diameter of any two nodes in the path lengths. This path may pass through the root.

Examples

Given a binary tree

          1
         / \
        2   3
       / \     
      4   5   

Return 3, which is the path length [4,2,1,3] or [5,2,1,3].

note:

Path length between two nodes is represented by the number of edges therebetween.

Thinking

Corresponds to the depth calculated binary tree, for each node, the left and right subtrees of the depth calculation, by the depth of the left and right subtrees clearing a path length of the current node. Then return count parent node of the current node to its depth.

Code

/**
 * 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 diameterOfBinaryTree(TreeNode* root) {
        if ( root == nullptr ) 
            return 0;

        int maxVal = 0;

        helper( root, maxVal );

        return maxVal;
    }

    int helper( TreeNode* root, int& maxVal ) {
        if ( root == nullptr ) return 0;

        int left = helper( root->left, maxVal );
        int right = helper( root->right, maxVal );

        int tempDiameter = right + left;
        maxVal = max( maxVal, tempDiameter );

        return max( left, right ) + 1;
    }
};
He published 183 original articles · won praise 43 · views 60000 +

Guess you like

Origin blog.csdn.net/m0_37822685/article/details/104769665