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

Diameter of Binary Tree

时间:2018-10-15 11:47:32      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:repr   pat   com   present   example   length   between   The   tween   

  

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.

 

思路

这个问题可以分两个方面来考虑: 
1. 最长路径经过根节点:那么根节点的左子树的深度和右子树的深度就是我们的结果 
2. 最长路径没有经过根节点:这个问题就分为两个子问题,分别设置新的根节点为其左子节点和右子节点,然后重复步骤 1

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int max = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        if(root==null) return 0;
        int rightDepth = treeDepth(root.right);
        int leftDepth = treeDepth(root.left);
        int sum = rightDepth+leftDepth;
        max = Math.max(Math.max(diameterOfBinaryTree(root.left),diameterOfBinaryTree(root.right)), sum);
        return max;
    }
    
    public int treeDepth(TreeNode node)
    {
        if(node==null) return 0;
        return Math.max(treeDepth(node.right),treeDepth(node.left))+1;
        
    }
}

 

Diameter of Binary Tree

标签:repr   pat   com   present   example   length   between   The   tween   

原文地址:https://www.cnblogs.com/hygeia/p/9789049.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!