有一棵二叉树,树上每个点标有权值,权值各不相同,请设计一个算法算出权值最大的叶节点到权值最小的叶节点的距离。二叉树每条边的距离为1,一个节点经过多少条边到达另一个节点为这两个节点之间的距离。
给定二叉树的根节点root,请返回所求距离。
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
<span style="color: rgb(0, 188, 155); font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; font-size: 13px; line-height: 18px; white-space: nowrap;">//典型的二进制编码题,算出叶子节点二进制编码,再比编码,计算后缀长度和</span>
public class Tree {
private StringBuilder maxCode = new StringBuilder();
private StringBuilder minCode = new StringBuilder();
private int min = Integer.MAX_VALUE;
private int max = Integer.MIN_VALUE;
public void preOrder(TreeNode root, char c, StringBuilder code) {
if(root != null) {
code.append(c);
if(root.left == null && root.right == null) {
if(min > root.val) {
min = root.val;
minCode = code;
}
if(max < root.val) {
max = root.val;
maxCode = code;
}
}
preOrder(root.left, '0', new StringBuilder(code));
preOrder(root.right, '1', new StringBuilder(code));
}
}
public int getDis(TreeNode root) {
preOrder(root, '0', new StringBuilder());
int index = 0;
for(index = 0; index < (maxCode.length() > minCode.length() ? maxCode.length() : minCode.length()); index++) {
if(maxCode.charAt(index) != minCode.charAt(index)) {
break;
}
}
return (maxCode.substring(index).length() + minCode.substring(index).length());
}
}