LeetCode Algorithm 543. 二叉树的直径
生活随笔
收集整理的這篇文章主要介紹了
LeetCode Algorithm 543. 二叉树的直径
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
543. 二叉樹的直徑
Ideas
這題貌似也在左神算法里見過。
基本思想就是遞歸,根節點從左子樹獲得一個想要的信息,從右子樹獲得一個想要的信息,然后對兩個信息進行處理。
其實可以把直徑分成兩半看:從根節點到左子樹的葉子結點的最長路徑+根節點到右子樹的葉子結點的最長路徑-1。
然后就簡單了,問題就轉變成了求二叉樹的深度。
Code
C++
class Solution {int ans = 1;int depth(TreeNode* rt) {if (rt == NULL) {return 0;}int l_depth = depth(rt->left);int r_depth = depth(rt->right);ans = max(ans, l_depth + r_depth + 1);return max(l_depth, r_depth) + 1;} public:int diameterOfBinaryTree(TreeNode* root) {depth(root);return ans - 1;} };總結
以上是生活随笔為你收集整理的LeetCode Algorithm 543. 二叉树的直径的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode Algorithm 5
- 下一篇: LeetCode Algorithm 7