1. 程式人生 > >Leetcode 543. Diameter of Binary Tree

Leetcode 543. Diameter of Binary Tree

文章作者:Tyan
部落格:noahsnail.com  |  CSDN  |  簡書

1. Description

Diameter of Binary Tree

2. Solution

/**
 * 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;
    }
};

Reference

  1. https://leetcode.com/problems/diameter-of-binary-tree/description/