LeetCode 543. Diameter of Binary Tree【Java】

Title description

The diameter of the binary tree

AC code

Enumerate the maximum value of the path passing through each node, and update the global diameter according to this value. The final result is the diameter . The left and right subtrees are independent, so to get the maximum path of the current node, you only need to get the maximum value of the left path and the maximum value of the right path, and then add it. In fact, it is to find the left and right subtrees. The sum of depth.
Note: It is also mentioned in the title, it does not have to go through the root node.
Insert picture description here

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int len=0;
    public int diameterOfBinaryTree(TreeNode root) {
        dfs(root);
        return len;
    }

    int dfs(TreeNode root){
        if(root==null)
            return 0;
        int left=dfs(root.left);
        int right=dfs(root.right);
        //更新最长的直径
        len=Math.max(len,left+right);
        //从当前节点往下走的最大值(从这个点向下往左和往右走中取最大的)
        return Math.max(left+1,right+1);
    }
}
Published 201 original articles · Like9 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/weixin_40992982/article/details/105476223