Diameter of Binary Tree

2019-05-25 22:39:40 浏览数 (1)

1. Description

2. Solution

代码语言: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 {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        if(!root) {
            return 0;
        }
        int diameter = 0;
        dfs(root, diameter);
        return diameter;
    }
    
private:
    int dfs(TreeNode* root, int& diameter) {
        if(!root) {
            return 0;
        }
        int left = dfs(root->left, diameter);
        int right = dfs(root->right, diameter);
        diameter = max(diameter, left   right);
        return max(left, right)   1;
    }
};

0 人点赞