【LeetCode】 543. Diameter of Binary Tree 二叉树的直径(Easy)(JAVA)

【LeetCode】 543. Diameter of Binary Tree 二叉树的直径(Easy)(JAVA)

题目地址: https://leetcode.com/problems/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.

题目大意

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。

解题方法

任意两个结点路径长度 == 任意节点的左右子树的最长路径
遍历,然后计算,得出所有节点的左右节点的和的最大值

/**
 * 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) {
        height(root);
        return max;
    }

    public int height(TreeNode root) {
        if (root == null) return 0;
        int left = height(root.left);
        int right = height(root.right);
        if ((left + right) > max) max = left + right;
        return Math.max(left, right) + 1;
    }
}

执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 39.3 MB, 在所有 Java 提交中击败了 5.08% 的用户

你可能感兴趣的:(Leetcode,二叉树,leetcode,java,算法)