[leetcode] Diameter of Binary Tree

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 longestpath 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.


分析:题目翻译一下:一个二叉树,要求找二叉树中最远的两个节点之间的距离,距离定义为路径上连边的个数。
两个点的距离,很容易想到最远的两个点肯定在某个树的左右子树上,因此想到计算树的高度。用res来保存以某个节点root为根节点的子树上最远的距离。DFS方法其实也就是对求树的高度算法的改变,还是很容易想到的,代码如下:
 1 class Solution {
 2    int res = 0;
 3     public int diameterOfBinaryTree(TreeNode root) {
 4         if ( root == null ) return 0;
 5         helper(root);
 6         return res-1;
 7     }
 8     private int helper(TreeNode root) {
 9         if ( root == null ) return 0;
10         int left_high = helper(root.left);
11         int right_high = helper(root.right);
12         res = Math.max(res,left_high+right_high+1);
13 //        System.out.println(root.val+"   "+res);
14         return Math.max(left_high,right_high)+1;
15     }
16 }

      我们以上面的例子来讲解一下代码的流程:

4   1
5   1
2   3
3   3
1   4

      13行的输出语句格式:第一列是遍历的节点,第二列是res值。可以看到从叶节点向上遍历,先左子树,后右子树。

猜你喜欢

转载自www.cnblogs.com/boris1221/p/9316663.html