543. Diameter of Binary Tree | 二叉树的“直径”

    xiaoxiao2021-04-17  43

    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.

    Subscribe to see which companies asked this question.

    思路:先用的方法是只计算根节点的左右节点的高度,然后返回两个数相加的和,但是发现有些情况并没有通过,是因为可能最长路径并不是通过根节点的,例如左孩子只有一个节点,但是右孩子的左右节点都很多,所以最后的方法是在计算二叉树的高度的时候比较左右子节点的高度的和与当前最长路径比较,最后返回最长路径。

    /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { int maxNum = 0; public int diameterOfBinaryTree(TreeNode root) { int n = 0; if (root == null || (root.left == null && root.right == null)) { return 0; } helper(root); return maxNum; } public int helper(TreeNode root) { if (root == null) { return 0; } int left = helper(root.left); int right = helper(root.right); if (left + right > maxNum) { maxNum = left + right; } return left > right ? left + 1 : right + 1; } }

    转载请注明原文地址: https://ju.6miu.com/read-674413.html

    最新回复(0)