《程序员代码面试指南》第三章 二叉树问题 二叉树节点间的最大距离问题

题目

二叉树节点间的最大距离问题

java代码

package com.lizhouwei.chapter3;

/**
 * @Description:二叉树节点间的最大距离问题
 * @Author: lizhouwei
 * @CreateDate: 2018/4/16 19:33
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter3_20 {
    public int maxDistance(Node head) {
        int[] record = new int[1];
        return postOrder(head, record);
    }

    public int postOrder(Node head, int[] record) {
        if (head == null) {
            record[0] = 0;
            return 0;
        }
        int lM = postOrder(head.left, record);//head的左子树中最远的距离
        int leftMax = record[0];//head的左子树离叶子节点最远的距离
        int rM = postOrder(head.right, record);//head的右子树中最远的距离
        int righMax = record[0];//head的右子树离叶子节点最远的距离
        //head左右子树离叶子节点最远的距离最大的一个,再加上1 就是此节点中里叶子节点最大的距离
        record[0] = Math.max(leftMax, righMax) + 1;
        int curMax = leftMax + righMax + 1;//通过head节点的距离
        return Math.max(Math.max(lM, rM), curMax);
    }

    //测试
    public static void main(String[] args) {
        Chapter3_20 chapter = new Chapter3_20();
        int[] arr = {4, 2, 5, 1, 3, 6, 7};
        Node head = NodeUtil.generTree(arr, 0, arr.length - 1);
        System.out.print("head二叉树节点间最大距离为:" + chapter.maxDistance(head));
    }
}
posted @ 2018-04-16 19:52  lizhouwei  阅读(131)  评论(0编辑  收藏  举报