码迷,mamicode.com
首页 > 其他好文 > 详细

14.Diameter of Binary Tree(二叉树的直径)

时间:2019-04-15 20:29:09      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:nod   答案   path   repr   max   题目   not   pre   子节点   

Level:

??Easy

题目描述:

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.

思路分析:

??题目要求找出二叉树的直径,二叉树的直径的定义是,任意两节点之间的最长路径,这个路径不一定会经过根节点。我们的解题思路是,最长路径肯定是以某个节点为中转,分别从这个节点的左右子节点延伸到叶子节点的两条无转向的路径和。所以只需要求出所有节点作为中转节点的路径长度,取其中最大的就得到了答案。

代码:

public class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int x){
        val=x;
    }
}
public class Solution{
    public int diameterOfBinaryTree(TreeNode root){
        if(root==null)
            return 0;
        int res=depth(root.left)+depth(root.right);
        int ledia=diameterOfBinaryTree(root.left);
        int ridia=diameterOfBinaryTree(root.right);
        return Math.max(Math.max(res,ledia),ridia);
    }
    public int depth(TreeNode root){
        if(root==null)
            return 0;
        int left=depth(root.left);
        int right=depth(root.right);
        return Math.max(left,right)+1;
    }
}

14.Diameter of Binary Tree(二叉树的直径)

标签:nod   答案   path   repr   max   题目   not   pre   子节点   

原文地址:https://www.cnblogs.com/yjxyy/p/10712402.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!