543. Diameter of Binary Tree

一、题目

  1、审题 

  

  2、分析

    求一棵二叉树中两个节点相连的路径中的最多的边数。

二、解答

  1、思路

    等价于求一个节点作为根节点时,Max (左孩子的深度 + 右孩子深度).

    ① 、采用全局变量 max 记录 Max(左孩子深度 + 右孩子深度)

    ②、新建一个 getMaxDepth(root) 方法,该方法返回此 root 节点的最大深度(为左子树深度 或 右子树深度 + 1)

      同时,方法体内 更新 max 值;

  

    int max = 0;
    // 最长的左子树的深度 + 右子树的深度
    public int diameterOfBinaryTree(TreeNode root) {
        getMaxDepth(root);
        return max;
    }

    private int getMaxDepth(TreeNode node) {
        if(node == null)
            return 0;
        
        int left = getMaxDepth(node.left);
        int right = getMaxDepth(node.right);
        
        max = Math.max(max, left + right);
        
        return Math.max(left, right) + 1;
    }
原文地址:https://www.cnblogs.com/skillking/p/11208893.html