【LeetCode】Diameter of Binary Tree 解题报告

来源:互联网 发布:美图秀秀批处理mac版 编辑:程序博客网 时间:2024/05/29 11:19

【LeetCode】Diameter of Binary Tree 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/diameter-of-binary-tree/#/description

题目描述:

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.

Ways

这个题当然想到是递归。但是如何递归呢。看叶子节点的左右子树的深度都是0,那么,它的深度是0,一个数的深度是其左右子树的最大值+1。

树总的最大宽度是其左右子树高度的和中的最大值。

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

Date

2017 年 4 月 21 日

0 0