Java 计算路径长度以在二叉搜索树中查找最大值

Java 计算路径长度以在二叉搜索树中查找最大值,java,binary-search-tree,Java,Binary Search Tree,我如何在二元搜索树中找到用于查找最大值的路径长度(如表单A==>B一步和A==>B==>C三步) 这是我找到最大值的代码,我在她身上尝试了所有的解决方案,但没有找到答案 public int findMax(){ if(root == null){ // check if the root is not empty return 0; } Node current = root; while(current

我如何在二元搜索树中找到用于查找最大值的路径长度(如表单A==>B一步和A==>B==>C三步) 这是我找到最大值的代码,我在她身上尝试了所有的解决方案,但没有找到答案

public int findMax(){
        if(root == null){ // check if the root is not empty 
            return 0;
        }
        Node current = root;
        while(current.rightChild != null){
        current =current.rightChild ;
    }
        return current.value ;
    }

如果要查找从根到最大值的路径长度,只需保留一个计数器并在while循环中增加它,这样每次遍历到下一个节点时,计数器都会增加一个

像这样的

class Holder {
    int length;
}

public int findMax(Holder holder) {
    Node current = root;
    Node result = null;
    while (current != null) {
        result = current;
        current = current.rightChild;
        if (current != null) {
            holder.length++;
        }
    }

    return result.value;
}

Holder.length
应在返回时保留长度。

二叉树不能保证平衡,因此您需要查看左右子树。很好地重复,类似这样:

public int findMax (Node root) {
   return findMaxWork (root, 0);
}

public int findMaxWork (Node node, int level) {

  int leftMax = level;
  if (node.left != null) leftMax = findMaxWork (node.left, level + 1);
  int rightMax = level;
  if (node.right != null) rightMax = findMaxWork (node.right, level + 1);
  return Math.max(leftMax, rightMax);
}