Método recursivo que retornar o pai de um nó

2 respostas
heliojr

Bom, to com uma dúvida no seguinte código, já tente ao invés de pai receber “no”, simplesmente retornar o no, o problema é que não está está parando aí e retornando, ele está passando para informação seguinte. se alguém pude me ajudar ficaria grato.

private Node busca_pai(char dado, Node no){ Node pai = no; if (no != null) { if (no.getEloEsquerdo() != null) { if (no.getEloEsquerdo().getDado() == dado) { this.setAchou(true); pai = no; } else { if (no.getEloDireito() != null) { if (no.getEloDireito().getDado() == dado){ this.setAchou(true); pai = no; } } } } if (this.isAchou() == true){ return pai; } else { busca_pai(dado, no.getEloEsquerdo()); busca_pai(dado, no.getEloDireito()); } } return pai; }

2 Respostas

herbertpimentel

amigo, não sei se vc conhece delphi, mas tenho um código aqui em dephi que faz uma arvore de n niveis. talvez ajude. Infelizmente não precisei fazer ainda em java por isso não tenho um código pra exemplificar. Não conseguir avaliar o seu código pela ausencia dos métodos getEloEsquerdo(), getEloDireito(), busca_pai(char, Node)…

espero que o código ajude…

unit untFraTreeViewPessoasCategoria;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ZPgSqlQuery, DBClient, Provider, DB, ZQuery, RXCtrls, StdCtrls,
ExtCtrls;

type

PIdPessCat = ^TIdPessCat;

TIdPessCat = record

Id: String;

//SomenteNome: Boolean;

end;
TFraTreeViewPessoasCategoria = class(TFrame)

TvPessCat: TTreeView;

RxLabel1: TRxLabel;

Panel2: TPanel;

Button1: TButton;

procedure Button1Click(Sender: TObject);

private

{ Private declarations }

no0: TTreeNode;

ind: integer; // indice para inserir no array

ISQL: string;
procedure LimpaTreeView;
procedure MontaTreeView(IdMae: String; NoMae: TTreeNode);
function GeraScriptInsercao: String;
procedure AjustaSequencia;
function PegaProxSeq: String;

public
{ Public declarations }

procedure InicializaFrame(Id: String);
function PegaId(var IdPessCat, DescPessCat: String): Boolean;
procedure SelecionaNo(Id: String);
procedure AdicionaNo(Filho: Boolean; descricao: String);
procedure Salvar;
procedure Excluir;
procedure Atualizar(descricao: String);
function SomenteNome(id: String): Boolean;

end;

implementation

uses untDMConsulta, SqlExpr;

{$R *.dfm}

{ TFraTreeViewPessoasCategoria }

procedure TFraTreeViewPessoasCategoria.InicializaFrame(Id: String);

begin

LimpaTreeView;

MontaTreeView(null,Nil);

if not ((Id = ‘’) or (id = 0)) then

SelecionaNo(Id);

end;
procedure TFraTreeViewPessoasCategoria.LimpaTreeView;

begin

TvPessCat.Items.Clear;

end;
procedure TFraTreeViewPessoasCategoria.MontaTreeView(IdMae: String;

NoMae: TTreeNode);

var

Operador: String;

iSql: String;

IdPessCat: PIdPessCat;

CdsQryTmp: TClientDataSet;

DspQryTmp: TDataSetProvider;

SQryTmp: TSQLDataSet;

begin

try

if UpperCase(IdMae) = NULL then

Operador := is

else

Operador := =;
{Cria componentes}

CdsQryTmp := TClientDataSet.Create(Application);

DspQryTmp := TDataSetProvider.Create(Application);

SQryTmp   := TSQLDataSet.Create(Application);
{ Desabilita controles para agilizar consultas }

CdsQryTmp.DisableControls;

SQryTmp.DisableControls;
{ Configura Componentes Criados }

DspQryTmp.Name := DspQryTmp + IntToStr(DspQryTmp.ComponentIndex);

DspQryTmp.Options := [poAllowCommandText];

SQryTmp.SQLConnection := DMCon.dbsgj;

DspQryTmp.DataSet := SQryTmp;

CdsQryTmp.ProviderName := DspQryTmp.Name;
{ Seleciona os Nós }
iSql := 'select id, descricao, fkpessoas_categoria from pessoas_categoria '
  + 'where fkpessoas_categoria ' + Operador + ' ' + IdMae + ' order by descricao';
DMcon.ExecutaSQL(CdsQryTmp,iSql);

{ Monta a Arvore }
while not CdsQryTmp.Eof do
begin
  { Adiciona TreeView }
   New(IdPessCat);
  IdPessCat^.Id := CdsQryTmp.FieldByName('id').AsString;
  if NoMae = nil then
    no0 := TvPessCat.Items.AddObject(NoMae, CdsQryTmp.FieldByName('descricao').AsString, IdPessCat)
  else
    no0 := TvPessCat.Items.AddChildObject(NoMae, CdsQryTmp.FieldByName('descricao').AsString, IdPessCat);

  { Busca Recursiva de Filhos }
  MontaTreeView(CdsQryTmp.FieldByName('id').AsString, no0);

  CdsQryTmp.Next;
end;
finally

FreeAndNil(CdsQryTmp);

FreeAndNil(DspQryTmp);

FreeAndNil(SQryTmp);

end;

end;
function TFraTreeViewPessoasCategoria.PegaId(var IdPessCat, DescPessCat: String)

:Boolean;

var

i: integer;

begin

Result := False;

IdPessCat := ‘’;

DescPessCat := ‘’;

for i := 0 to TvPessCat.Items.Count - 1 do

begin

if TvPessCat.Items[i].HasChildren then

Continue

else

if TvPessCat.Items[i].Selected then

begin

IdPessCat   := PIdPessCat(TvPessCat.Items[i].Data)^.Id;

// xyz

DescPessCat := TvPessCat.Items[i].Text;

Result := True;

Break;

end;

end;

end;
procedure TFraTreeViewPessoasCategoria.Button1Click(Sender: TObject);

begin

InicializaFrame(’’);

end;
procedure TFraTreeViewPessoasCategoria.SelecionaNo(Id: String);

var

i: integer;

begin

for i := 0 to TvPessCat.Items.Count - 1 do

begin

if PIdPessCat(TvPessCat.Items[i].Data)^.Id = Id then

begin

TvPessCat.Items[i].Selected := True;

Break;

end;

end;

end;
procedure TFraTreeViewPessoasCategoria.AdicionaNo(Filho: Boolean; descricao: String);

var

NoMae: TTreeNode;

IdPessCat: PIdPessCat;

begin

{ verifica se o Novo No Será ou Não um Filho }

if Filho then

begin

NoMae := TvPessCat.Selected;

end

else

begin

if TvPessCat.SelectionCount > 0 then

NoMae := TvPessCat.Selected.Parent

else

NoMae := Nil;

end;
{ Adiciona TreeView }

New(IdPessCat);

IdPessCat^.Id := ‘’;

if NoMae = nil then

TvPessCat.Items.AddObject(NoMae, descricao, IdPessCat)

else

TvPessCat.Items.AddChildObject(NoMae, descricao, IdPessCat)

end;
function TFraTreeViewPessoasCategoria.GeraScriptInsercao: String;

var

i: integer;

ins: string;

idSeq: String; { Sequencia }

begin
AjustaSequencia;

Result := ‘’;

ins := insert into pessoas_categoria(id,descricao,fkpessoas_categoria) values(;

for i := 0 to TvPessCat.Items.Count - 1 do

begin
if (PIdPessCat(TvPessCat.Items[i].Data)^.Id = '') then
    if (TvPessCat.Items[i].Parent <> nil) then
    begin
      idSeq := PegaProxSeq;
      Result := Result + ins + idSeq + ', ' + QuotedStr(TvPessCat.Items[i].Text)
        + ',' + PIdPessCat(TvPessCat.Items[i].Parent.Data)^.Id + ');' + #13;
      PIdPessCat(TvPessCat.Items[i].Data)^.Id := idSeq;
    end
    else
    begin
      idSeq := PegaProxSeq;
      Result := Result + ins + idSeq + ', ' + QuotedStr(TvPessCat.Items[i].Text)
        + ',null);' + #13;
      PIdPessCat(TvPessCat.Items[i].Data)^.Id := idSeq;
    end;

end;
end;

function TFraTreeViewPessoasCategoria.PegaProxSeq: String;

begin

with DMcon.qry4 do

begin

Close;

CommandText := ‘select nextval(’‘pessoas_categoria_id_seq’’)’;

DMCon.ExecutaSQL(dmcon.Qry4);

Result := Fields[0].AsString;

end;

end;
procedure TFraTreeViewPessoasCategoria.AjustaSequencia;

begin

ISQL := select setval(’‘pessoas_categoria_id_seq’’, (

+  select max(id) from pessoas_categoria

+  where id <= (select faixafinal_id from comarca where ipservidor::::inet = (select inet_server_addr()))

+  ));’;

DMCon.BatchSQL(ISQL);

end;
procedure TFraTreeViewPessoasCategoria.Salvar;

begin

DMCon.BatchSQL(GeraScriptInsercao);

end;
procedure TFraTreeViewPessoasCategoria.Excluir;

begin

ISQL := 'delete from pessoas_categoria where id =  + PIdPessCat(TvPessCat.Selected.Data)^.Id;

DMCon.BatchSQL(ISQL);

end;
procedure TFraTreeViewPessoasCategoria.Atualizar(descricao: String);

begin

isql := 'update pessoas_categoria set descricao =  + QuotedStr(descricao)

+  where id =  + PIdPessCat(TvPessCat.Selected.Data)^.Id;

DMCon.BatchSQL(ISQL);

end;
function TFraTreeViewPessoasCategoria.SomenteNome(id: String): Boolean;

var

i: integer;

noAtual: TTreeNode;

begin

noAtual := nil;

Result := False;
{ Verifica o no a ser perquisado }

for i := 0 to TvPessCat.Items.Count - 1 do

begin

if PIdPessCat(TvPessCat.Items[i].Data)^.Id = Id then

begin

noAtual := TvPessCat.Items[i];

Break;

end;

end;
{ varre todos os pais em busca da informacao }

while noAtual <> nil do

begin

Result := (Result) or (PIdPessCat(noAtual.Data)^.Id = 3); { 3 - Autoridades }

if Result then Break;

noAtual := noAtual.Parent;

end;

end;

end.

ViniGodoy

Herbert, sempre que for postar código, seja lá em qual linguagem, use a tag code, como descrito neste artigo.

Criado 28 de maio de 2007
Ultima resposta 28 de mai. de 2007
Respostas 2
Participantes 3