leetcode - 543. 二叉树的直径
程序员文章站
2022-05-20 10:57:14
...
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
示例 :
给定二叉树
解题思路:使用递归,注意递归和迭代的区别
class Solution {
private:
int sum = 0;
public:
int depth(TreeNode* root)
{
if(root == NULL)
return 0;
int L = depth(root->left); # 递归假定当前左子树的长度已经获得
int R = depth(root->right); # 递归假定当前右子树的长度已经获得
sum = max(sum,L+R); # 计算以当前节点为根节点事最长长度的直径
return max(L,R)+1;
}
int diameterOfBinaryTree(TreeNode* root) {
depth(root);
return sum;
}
};
推荐阅读
-
C++实现LeetCode(111.二叉树的最小深度)
-
leetcode 113 剑指offer 面试题34. 二叉树中和为某一值的路径(python3)
-
LeetCode第958题 二叉树的完全性检验
-
Leetcode刷题记录——958. 二叉树的完全性检验
-
leetcode 第 958 题:二叉树的完全性检验(C++)
-
leetcode 958 二叉树的完全性检验(超简洁写法)
-
leetcode 958. 二叉树的完全性检验(输出是否是完全二叉树 dfs/bfs每次假如队列的时候判断 值是不是sz)
-
Java实现 LeetCode 637 二叉树的层平均值(遍历树)
-
LeetCode637. 二叉树的层平均值(层序遍历)
-
【树】leetcode_637_二叉树的层平均值