LeetCode OJ 543 Diameter of Binary Tree [Easy]

来源:互联网 发布:老网络歌曲大全 编辑:程序博客网 时间:2024/06/08 01:59

题目描述:

Given a binary tree,you need to compute the length of the diameter of the tree. The diameter of abinary 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 isthe length of the path [4,2,1,3] or [5,2,1,3].

题目理解:

给一个二叉树,计算二叉树的最长的路径

题目分析:

1.  对于每一个节点,通过该节点的最长路径 = 该节点左子数最大深度 + 该节点右子数最大深度;

2.  计算通过每一节点的最长路径,取最大值;

3.  使用递归,极限情况是子树为null,此时返回0,即子树的深度为0

4.  使用递归,非极限情况,返回的是左/右子树的深度,左/右子树的深度  = max(子树的左子树深度left,子树的右子树深度right)+1, 这里的1表示加上该子树的根节点。

5.  对下图的递归的解释:

             1

            / \

          2   3

         / \    

       4   5

              \

               6

       4/6/3的左右子树深度为0;

       5的左子树深度为0,右子树(6)深度为0+1=1;

       2的左子树(4)深度为0+1=1,右子树(5)深度为 = max((5)的左子树深度0,(5)的右子树深度1)+1=2;

       1右子树(3)的深度为0+1=1,的左子树(2)深度为 = max((2)的左子树深度1,(2)的右子树深度2)+1=3;

题目解答:

public class Solution {    int max = 0;    public int diameterOfBinaryTree(TreeNoderoot) {        maxDepth(root);        return max;    }    private int maxDepth(TreeNoderoot) {        if (root== null) return 0;        intleft = maxDepth(root.left);        int right= maxDepth(root.right);        max =Math.max(max, left + right);        return Math.max(left,right) + 1;    }}


 

 

原创粉丝点击