Leetcode 543. Diameter of Binary Tree

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/84945060

文章作者: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/

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试