Diameter of Binary Tree

Posted hygeia

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode题解之Diameter of Binary Tree

LeetCode 543. Diameter of Binary Tree 解题笔记

LeetCode 543. Diameter of Binary Tree 解题笔记

Diameter of Binary Tree

543. Diameter of Binary Tree

543. Diameter of Binary Tree