1. 题目

Leetcode#543. 二叉树的直径,C++实现

2. 方法一

2.1. 代码

class Solution {
    int max_num=0;
public:
    int diameterOfBinaryTree(TreeNode* root) {
        depth(root);
        return max_num;
    }
    int depth(TreeNode* root)
    {
        if(root==NULL) return 0;
        int left=depth(root->left);
        int right=depth(root->right);
        max_num=max(max_num,left+right);
        return max(left,right)+1;
    }
};

2.2. 结果

Leetcode#543. 二叉树的直径,C++实现

相关文章: