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


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

}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */

猜你喜欢

转载自www.cnblogs.com/laydown/p/12977187.html