LeetCode 543. Diameter of Binary Tree (two nodes longest path)

Meaning of the questions: find the longest path tree any two nodes.

Analysis: The longest path through the root of a subtree must, obviously, both ends of the longest path in either the root node or a leaf, the length of the longest path for the left sub certain subtree + high tree height right subtree.

/**
 * 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 = 0;
    int maxDepth(TreeNode* root){
        if(root == NULL) return 0;
        int leftdepth = maxDepth(root -> left);
        int rightdepth = maxDepth(root -> right);
        ans = max(ans, leftdepth + rightdepth);
        return max(leftdepth, rightdepth) + 1;
    }
    int diameterOfBinaryTree(TreeNode* root) {
        maxDepth(root);
        return ans;
    }
};

 

Guess you like

Origin www.cnblogs.com/tyty-Somnuspoppy/p/12387588.html