C/C++编程题刷题:leetcode 543. 二叉树的直径
2020-08-24 12:22
225 查看
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
示例 :
给定二叉树
[code] 1 / \ 2 3 / \ 4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
[code]/** * 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 { int ans; public: int diameterOfBinaryTree(TreeNode* root) { ans = 0; dfs(root); return ans; } int dfs(TreeNode* p){ if(p==nullptr) return 0; int L = dfs(p->left); int R = dfs(p->right); ans = max(ans,L+R); return max(L,R)+1; } };
相关文章推荐
- leetcode 543. 二叉树的直径
- Leetcode543. 二叉树的直径
- Leetcode 543. 二叉树的直径
- C/C++编程题刷题:leetcode 958. 二叉树的完全性检验
- Leetcode 543. 二叉树的直径-----python
- C/C++编程题刷题:leetcode 814. 二叉树剪枝
- leetcode 543. 二叉树的直径
- C/C++编程题刷题:leetcode415. 字符串相加
- LeetCode二叉树的最大深度C++版
- leetcode笔试题二叉树的前序、中序、后序遍历的递归和循环c++实现
- LeetCode257-二叉树的所有路径(C++递归实现)
- Leetcode 297. 二叉树的序列化与反序列化 C++
- Leetcode 226. 翻转二叉树 C++
- leetcode:654最大二叉树(C++)
- leetcode-543 二叉树的直径 Python
- Go语言:LeetCode-二叉树的直径
- LeetCode100-相同的二叉树(C++实现)
- Leetcode 257. 二叉树的所有路径 C++
- LeetCode 106 从中序与后序遍历序列构造二叉树 (C++)
- Leetcode 543 二叉树的直径 (二叉树的理解和操作)