import java.util.Stack;
// 我的思想路是,无论这个距离有多长,由于是二叉树,最大距离必产生在该树的某一个节点上
// 对所有节点的左右子树计算后,相加再加一,找出最大值
public class Finder{
public static Stack<Node> stack = new Stack<>();
// 递归的方式计算该节点的最大深度
public static int deeps(Node root) {
if(root == null) {
return 0;
}
if(root.left == null && root.right == null) {
return 1;
}
else if(root.left == null && root.right != null) {
return deeps(root.right) + 1;
}
else if(root.left != null && root.right == null) {
return deeps(root.left) + 1;
}
else {
return deeps(root.left) > deeps(root.right) ?
deeps(root.left) + 1: deeps(root.right) + 1;
}
}
// 分别计算该节点的左右深度后,相加,再加入自己这个节点
public static int nodeMaxDistance(Node node) {
int leftMax = deeps(node.left);
int rightMax = deeps(node.right);
return leftMax+rightMax+1;
}
// 先序遍历访问所有节点,计算出距离的最大值
public static int treeMaxDistance(Node root) {
int max = 0;
Node pointer = root;
while(!stack.isEmpty() || pointer != null) {
if(pointer != null) {
int temp = nodeMaxDistance(pointer);
if(temp > max)
max = temp;
if(pointer.right != null)
stack.push(pointer.right);
pointer = pointer.left;
}
else {
pointer = stack.pop();
}
}
return max;
}
public static void main(String[] args) {
Node root = new Node(new Node(null, null), new Node(null, null));
root.left.left = new Node(null, new Node(null, null));
System.out.println(Finder.treeMaxDistance(root));
}
}
class Node{
Node left;
Node right;
public Node(Node left, Node right) {
this.left = left;
this.right = right;
}
}