leetcode 543. Diameter of Binary Tree
2017-07-23 16:52
225 查看
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
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.
有这几个例子看一下。
1、
这个返回1。
2、
这个返回3
3、
这个返回8. (是 -9的左子树 加上 -9的右子树)
由此可以看出,我们需要比较每个结点的“左子树高度+右子树高度”,然后取最大的那个即是结果。我们可以使用高度(即层数,包括顶点的层数)来进行递归。
大神也跟我过程一样!
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.
有这几个例子看一下。
1、
1 / 2
这个返回1。
2、
这个返回3
3、
这个返回8. (是 -9的左子树 加上 -9的右子树)
由此可以看出,我们需要比较每个结点的“左子树高度+右子树高度”,然后取最大的那个即是结果。我们可以使用高度(即层数,包括顶点的层数)来进行递归。
package leetcode; public class Diameter_of_Binary_Tree_543 { public int diameterOfBinaryTree(TreeNode root) { int[] max=new int[1]; cengshu(root, max); return max[0]; } public int cengshu(TreeNode node,int[] max){//连带node自己的总共层数 if(node==null){ return 0; } int left=cengshu(node.left, max); int right=cengshu(node.right, max); if(left+right>max[0]){ max[0]=left+right; } return Math.max(left, right)+1; } }使用max[]是因为数组参数传的是引用而不是值,因此max[]就相当于一个全局变量了,所有改变都改的同一个max。
大神也跟我过程一样!
相关文章推荐
- Leetcode 543. Diameter of Binary Tree
- LeetCode 111. Minimum 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 111. Minimum Depth of Binary Tree
- leetcode 543. Diameter of Binary Tree
- [Leetcode] Binary tree-- 637. Average of Levels in Binary Tree
- LeetCode 104. Maximum Depth 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
- 【LeetCode】111. Minimum Depth of Binary Tree
- LeetCode之104. Maximum Depth of Binary Tree
- [Leetcode] Binary tree--112. Path Sum
- leetcode 107 Binary Tree Level Order Traversal II
- leetcode 每日一题 111. Minimum Depth of Binary Tree
- Leetcode Everyday: 104. Maximum Depth of Binary Tree
- <LeetCode OJ> Invert Binary Tree【226】