首页 > 其他 > 详细

543. Diameter of Binary Tree

时间:2019-07-18 20:02:08      阅读:50      评论:0      收藏:0      [点我收藏+]

一、题目

  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;
    }

 

543. Diameter of Binary Tree

原文:https://www.cnblogs.com/skillking/p/11208893.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!