Leetcode 树-543-二叉树的直径

2021-09-18 15:24:05 浏览数 (1)

DFS解法

代码语言:javascript复制
/**
 * 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 {
private:
    int max_len = 0;
public:
    int dfs(TreeNode* root) {
        if (root == nullptr) return 0;
        int left = dfs(root->left);
        int right = dfs(root->right);
        int depth = max(left, right)   1;
        if(max_len < left   right)
            max_len = left   right;
        return depth;
    }
    int diameterOfBinaryTree(TreeNode* root) {
        dfs(root);
        return max_len;
    }
};
dfs

0 人点赞