leetcode编程记录9 #543 Diameter of Binary Tree
2017-10-27 22:49
375 查看
leetcode编程记录9 #543 Diameter of Binary Tree
标签(空格分隔): leetcode这次是一道关于树的题目,这是一个比较简单的题目,找出在树中的一条最长的路径的长度。题目如下:
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.
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.
题目理解与分析:
这道题目比较简单,只要实现求树的高度的函数,然后在递归调用该函数的过程中,存下最大路径,然后最后得到的就是一条最长路径。
代码如下:
class Solution { public: int diameterOfBinaryTree(TreeNode* root) { result = 0; if (root != NULL) { int example = height(root->left) + height(root->right); return max(example, result); } else { return 0; } } //private: int result; int max(int a, int b) { if (a > b) { return a; } else { return b; } } int height(TreeNode* root) { if (root == NULL) { return 0; } else { int left = height(root->left); int right = height(root->right); result = max(result, left + right); return max(left, right) + 1; } } };
相关文章推荐
- leetcode(543). Diameter of Binary Tree
- LeetCode 543: Diameter of Binary Tree
- LeetCode 543 Diameter of Binary Tree
- LeetCode 543---- Diameter of Binary Tree
- leetcode编程记录13 #637 Average of Levels in Binary Tree
- leetcode543 Diameter of Binary Tree
- 【Leetcode-easy-543】Diameter of Binary Tree
- leetcode(543):Diameter of Binary Tree
- LeetCode - 543 - Diameter of Binary Tree
- Leetcode在线编程minimum-depth-of-binary-tree
- leetcode:104 Maximum Depth of Binary Tree-每日编程第三题
- leetcode:111 Minimum Depth of Binary Tree-每日编程第三十题
- [124]. Binary Tree Maximum Path Sum, [543]. Diameter of Binary Tree
- LeetCode OJ 543 Diameter of Binary Tree [Easy]
- leetcode-504-Diameter of Binary Tree
- [LeetCode] Diameter of Binary Tree 二叉树的直径
- leetcode编程记录8 #107 Binary Tree Level Order Traversal II
- LeetCode——Diameter of Binary Tree
- leetcode[Diameter of Binary Tree]//待整理多种解法
- 【LeetCode】Diameter of Binary Tree 解题报告