【同124】LeetCode 543. Diameter of Binary Tree

LeetCode 543. Diameter of Binary Tree
Solution1:我的答案
思路和方法就是同124题的

/**
 * 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) return 0;
        int ans = 0;
        my_longpath(root, ans);
        return ans;
    }

    int my_longpath(TreeNode* root, int& ans) {
        if (!root) return 0;
        int l =  my_longpath(root->left, ans);
        int r = my_longpath(root->right, ans);
        ans = max(ans, l + r);
        return 1 + max(l, r);
    }
};

猜你喜欢

转载自blog.csdn.net/allenlzcoder/article/details/80871592