[LeetCode] Binary Tree diameter 543. Diameter of the binary tree (Easy) (JAVA)

[LeetCode] Binary Tree diameter 543. Diameter of the binary tree (Easy) (JAVA)

Topic Address: https://leetcode.com/problems/diameter-of-binary-tree/

Subject 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.

Subject to the effect

Given a binary tree, you need to calculate the length of its diameter. A binary tree is the maximum length of the diameter of any two nodes in the path lengths. This path may pass through the root.

Problem-solving approach

The longest path left subtree path lengths of any two nodes == any node
and traversal, then calculated the all nodes around node maximum

/**
 * 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;
    }
}

When execution: 0 ms, defeated 100.00% of all users to submit in Java
memory consumption: 39.3 MB, beat the 5.08% of all users to submit in Java

Published 81 original articles · won praise 6 · views 2295

Guess you like

Origin blog.csdn.net/qq_16927853/article/details/104768840