leetcode 543. Diameter of Binary Tree
2018-03-01 09:28
381 查看
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
题目大意:求二叉树中任意两点的最长路径长度。
思路:分别求当前结点的左子树深度和右子树深度。将其相加得到x,并保留x的最大值。
Example: Given a binary tree 1 / \ 2 3 / \ 4 5 Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. Note: The length of path between two nodes is represented by the number of edges between them.
题目大意:求二叉树中任意两点的最长路径长度。
思路:分别求当前结点的左子树深度和右子树深度。将其相加得到x,并保留x的最大值。
/** * 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 { public: int Max = 0; int dfs(TreeNode* root) { if (root == nullptr) return 0; int d1 = 0; int d2 = 0; d1 = dfs(root->left); ++d1; d2 = dfs(root->right); ++d2; Max = max(d1 + d2 - 2, Max); return max(d1, d2); } int diameterOfBinaryTree(TreeNode* root) { dfs(root); return Max; } };
相关文章推荐
- LeetCode 545. Boundary of Binary Tree
- LeetCode-104. Maximum Depth of Binary Tree
- LeetCode:Binary Tree Traversal(二叉树遍历非递归)
- LCP104 LeetCode 104. Maximum Depth of Binary Tree
- LeetCode: Binary Tree Sum相关题目合集
- [LeetCode] 543. Diameter of Binary Tree
- LeetCode之104. Maximum Depth of Binary Tree
- leetcode-104. Maximum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- leetcode记录 104. Maximum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- leetcode 545. Boundary of Binary Tree
- leetcode 104. Maximum Depth of Binary Tree
- Leetcode 654. Maximum Binary Tree 最大二叉树 解题报告
- [leetcode] 543. Diameter of Binary Tree
- leetcode 104. Maximum Depth of Binary Tree
- [LeetCode]111. Minimum Depth of Binary Tree
- LeetCode——111. Minimum Depth of Binary Tree
- [勇者闯LeetCode] 104. Maximum Depth of Binary Tree