• 给定一棵二叉树的头节点,求这棵树上的最大距离



    /**
    * 给定一棵二叉树的头节点,求这棵树上的最大距离
    */
    public class MaxDistance {

    public static int maxDistance(Node head) {
    return process(head).maxDistance;
    }

    public static ResultInfo process(Node node) {
    if (node == null) {
    return new ResultInfo(0, 0);
    }
    ResultInfo leftInfo = process(node.left);
    ResultInfo rightInfo = process(node.right);
    int height = Math.max(leftInfo.height, rightInfo.height) + 1;
    int maxDistance = Math.max(Math.max(leftInfo.maxDistance, rightInfo.maxDistance), leftInfo.height + rightInfo.height + 1);
    return new ResultInfo(maxDistance, height);
    }

    /**
    * 向左右子树索要信息
    */
    public static class ResultInfo {

    // 当前最大距离
    public int maxDistance;

    // 当期高度
    public int height;

    public ResultInfo(int dis, int h) {
    maxDistance = dis;
    height = h;
    }

    }

    /**
    * 二叉树结构
    */
    public static class Node {

    public Node left;

    public Node right;

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    ESP8266 A0的使用
    电脑总是被乱装各种软件怎么办?那就设置一个密码吧!
    笔记本光驱位改装固态系统硬盘教程
    任务管理器无法呼出
    Python stomp 介绍与代码
    Power(x,y)
    旋转图像
    字符串相乘
    缺失的正数
    外观数列
  • 原文地址:https://www.cnblogs.com/laydown/p/12977187.html
Copyright © 2020-2023  润新知