打印BST的直径

时间:2013-02-16 19:37:11

标签: java algorithm tree binary-search-tree

我编写了一个程序来查找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:最大深度找出树的高度。

由于

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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;

}

}