Leetcode学习笔记:#543. Diameter of Binary Tree

Leetcode学习笔记:#543. 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.

实现:

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

思路:
前序遍历二叉树,用max保存当前最大值并决定是否更新

上一篇:How to intercept any postback in a page? - ASP.NET


下一篇:js 引入外部文件之 script 标签