543. 二叉树的直径

传送门

代码

class Solution {
    private int ans = 1;
    public int diameterOfBinaryTree(TreeNode root) {
        dfs(root);
        return ans - 1;
    }
    public int dfs(TreeNode root) {
        if(root == null) return 0;
        int L = dfs(root.left);
        int R = dfs(root.right);
        ans = Math.max(L + R + 1,ans);
        return Math.max(L,R) + 1;
    }
}

思路

我原先写过一篇求树的直径的方法 树的直径 ,是算法竞赛中的解法

这题leetcode,就直接暴力可以了

首先,把每个结点都当成中点,那么这个节点所在的路径长度为 (L + R+1)

(L) 是左子树的长度 ,(R) 是右子树的长度

那么我们只要遍历每个结点,然后不断的更新这个全局变量 (ans) 即可

(dfs) 返回的是以 (root) 为根的高度,递归下去搜索就行

原文地址:https://www.cnblogs.com/lukelmouse/p/14220664.html