网易2016年实习生笔试题-二叉树
有一棵二叉树,树上每个点标有权值,权值各不相同,请设计一个算法算出权值最大的叶节点到权值最小的叶节点的距离。二叉树每条边的距离为1,一个节点经过多少条边到达另一个节点为这两个节点之间的距离。
给定二叉树的根节点root,请返回所求距离
思路:先找到最大最小的叶节点,然后把他们到LCA的距离相加即可
public class Tree {
int current_min;
int current_max;
// 给定二叉树的根节点root
public int getDis(TreeNode root) {
current_min = Integer.MAX_VALUE;
current_max = Integer.MIN_VALUE;
findMinMax(root);
TreeNode lca = findLCA(root, current_min, current_max);
int lev_lca = findLevel(root, lca.val);
int lev_min = findLevel(root, current_min);
int lev_max = findLevel(root, current_max);
return lev_min + lev_max - 2 * lev_lca;
}
// 中序遍历找最小、最大权值
public void findMinMax(TreeNode root) {
if (root == null)
return;
// 叶子节点
if (root.left == null && root.right == null) {
if (current_max < root.val)
current_max = root.val;
if (current_min > root.val)