您的位置:首页 > 其它

二叉树权值最大的叶子节点到权值最小的叶子节点的距离

2016-08-20 21:30 429 查看
有一棵二叉树,树上每个点标有权值,权值各不相同,请设计一个算法算出权值最大的叶节点到权值最小的叶节点的距离。二叉树每条边的距离为1,一个节点经过多少条边到达另一个节点为这两个节点之间的距离。 给定二叉树的根节点root,请返回所求距离。

真是醉了,看漏了叶子节点。

代码:

import java.util.*;

/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class Tree {

private TreeNode maxNode;
private TreeNode minNode;

private boolean stop = false;
private int result;

public int getDis(TreeNode root) {
if(root == null) {
return 0;
}

maxNode = root;
minNode = root;

getMaxAndMin(root);
getMaxLength(root);
return result;
}

private int[] getMaxLength(TreeNode root) {

if(root == null)
return new int[] {-1, -1};
if(root == maxNode)
return new int[] {0, -1};
if(root == minNode)
return new int[] {-1, 0};

int[] left = getMaxLength(root.left);
int[] right = getMaxLength(root.right);

int[] curResult = new int[]{Math.max(left[0], right[0]), Math.max(left[1], right[1])};

if(curResult[0] != -1)
curResult[0]++;
if(curResult[1] != -1)
curResult[1]++;

if(!stop && curResult[0] != -1 && curResult[1] != -1) {
result = curResult[0] + curResult[1];
stop = true;
}

return curResult;
}

private void getMaxAndMin(TreeNode root) {

if(root == null)
return;
if(root.left == null && root.right == null) {
if(root.val < minNode.val) {
minNode = root;
}
if(root.val > maxNode.val) {
maxNode = root;
}
}
getMaxAndMin(root.left);
getMaxAndMin(root.right);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐