zoukankan      html  css  js  c++  java
  • 给定一棵二叉树的头节点,求这棵树上的最大距离


    /**
    * 给定一棵二叉树的头节点,求这棵树上的最大距离
    */
    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;

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    [solution]xdebug正确配置,但不显示错误信息
    SIGCHLD信号
    sigsuspend
    信号引起的竞态
    智力面试题
    可重入和不可重入
    信号—信号处理函数(捕捉)
    PCB信号集
    信号产生的原因:
    信号初步
  • 原文地址:https://www.cnblogs.com/laydown/p/12977187.html
Copyright © 2011-2022 走看看