1 /*
 2  * @Author: yaodaoteng
 3  * @Date: 2020-11-13 16:45:46
 4  * @LastEditors: yaodaoteng
 5  * @LastEditTime: 2020-11-13 17:01:31
 6  * @FilePath: \git\leetcode\543.二叉树的直径.cpp
 7  */
 8 /*
 9  * @lc app=leetcode.cn id=543 lang=cpp
10  *
11  * [543] 二叉树的直径
12  */
13 
14 // @lc code=start
15 /**
16  * Definition for a binary tree node.
17  * struct TreeNode {
18  *     int val;
19  *     TreeNode *left;
20  *     TreeNode *right;
21  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
22  * };
23  */
24 class Solution {
25 public:
26 //思路:左子树的最大深度+右子树的最大深度为二叉树的直径
27     //这个递归可以想象成记忆化dfs或者说分治法,只有当最小子问题解决时(达到叶子节点时,深度为1),总问题才能得到解决(左子树的深度+右子树的深度)
28     int res;
29 
30     int depth(TreeNode* root){
31         if(root==nullptr)
32             return 0;// 访问到空节点了,返回0
33         //获得左右子树的深度
34         int left = depth(root->left);
35         int right = depth(root->right);
36         res = max(res, left + right);
37         //最小子问题:到达叶子节点时,深度为1。最小子问题解决,那么其他问题也都会解决。
38         return max(left,right)+1;
39     }
40     int diameterOfBinaryTree(TreeNode* root) {
41         if(root==nullptr)
42             return 0;
43         depth(root);
44         return res;
45     }
46 };
47 // @lc code=end