2016-01-25 56 views
0

我怎样才能找到我们用来在二叉搜索树中找到最大值的路径的长度(如表单A ====> B一步和A ====>乙====> 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 ; 
    } 

回答

0

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

0

这样的事情?

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应该保留返回的长度。

0

二叉树不能保证平衡,所以您需要查看左右儿童。好好回想起来,像这样:

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); 
}