0

我已经编写了一个程序来查找 BST 的直径......有人可以给我一些关于如何打印我找到的最大直径的节点(root.data)的想法吗?

private int maxDia(Node root) {
    if(root==null) {
        return 0;
    }
    else{

        int llen = maxDepth(root.left);
        int rlen = maxDepth(root.right);
        int ldia = maxDia(root.left);
        int rdia = maxDia(root.right);
        return Math.max(llen+rlen+1,Math.max(ldia,rdia));
    }
}

PS:最大深度找出树的高度。

谢谢

4

2 回答 2

0

伪代码:

printDia(root):
    if diameter goes through root:
        printFromDeepest(root.left)
        print(root)
        printToDeepest(root.right)
    else if diameter is in root.left:
        printDia(root.left)
    else:
        printDia(root.right)
于 2013-02-16T19:48:49.480 回答
0
 struct node
{    
node* left,right;
int data; 
};
struct path
{
 node *nodepointer;
 int length;
 };
int flag=0;

 node *x,*y,*lca;

 path *printpath(node *leaf,int d)
{
if(flag==0)
{
path *dia= new path;
dia->length=0;
dia->nodepointer=NULL;

if(leaf==NULL)
return dia;

path *a=new path;
path *b=new path;
a=printpath(leaf->left,d);
b=printpath(leaf->right,d);


if(a->length + b->length + 1 == d )
{
    lca=leaf;
    x=a->nodepointer;
    y=b->nodepointer;
    flag=1;
}

dia->length=max(a->length,b->length)+1;

if(a->length > b->length && a->nodepointer!=NULL)
{
    dia->nodepointer=a->nodepointer;
}
if(b->length >= a->length && b->nodepointer!=NULL)
{
    dia->nodepointer=b->nodepointer;
}
if(a->nodepointer==NULL && b->nodepointer==NULL)
{
        dia->nodepointer=leaf;
}

return dia;

}

}
于 2013-02-17T20:42:04.277 回答