Encontre o nó mais profundo de uma árvore binária


9

Escreva um programa que use uma árvore binária como entrada e produz o nó mais profundo e sua profundidade. Se houver um empate, imprima todos os nós envolvidos, bem como suas profundidades. Cada nó é representado como:

T(x,x)

T(x)

T

onde Té o identificador de um ou mais caracteres alfanuméricos e cada um xé outro nó.

Aqui está uma definição simples de uma árvore binária:

  • Na cabeça de uma árvore binária está um nó.
  • Um nó em uma árvore binária tem no máximo dois filhos.

Por exemplo, a entrada A(B(C,D(E)))(abaixo) seria exibida 3:E.

Árvore 1

Enquanto a árvore a seguir é um empate de três vias entre 5, 11 e 4, e sua profundidade também é 3 (começando em 0):

A entrada 2(7(2,6(5,11)),5(9(4)))(abaixo) seria exibida 3:5,11,4.

Árvore 2

Esse é o código golf, portanto o código mais curto medido em bytes vence.


@ eleitor próximo: do que você não sabe?
Jwosty

3
Talvez o fato de não haver especificação de entrada ou saída ou casos de teste para essas entradas e saídas.
Maçaneta

Tentando consertá-lo, mas meu telefone é péssimo ...: P é melhor ainda.
Jwosty

3
A primeira árvore não deve ser A (B (C, D (E))?
bakerg

11
@ Bakerg certo, meu erro. Fixo.
Jwosty

Respostas:


6

CJam, 49 47

0q')/{'(/):U;,+:TW>{T:W];}*TW={U]',*}*T(}/;W':@

 

0                 " Push 0 ";
q                 " Read the whole input ";
')/               " Split the input by ')' ";
{                 " For each item ";
  '(/             " Split by '(' ";
  )               " Extract the last item of the array ";
  :U;             " Assign the result to U, and discard it ";
  ,               " Get the array length ";
  +               " Add the top two items of the stack, which are the array length and the number initialized to 0 ";
  :T              " Assign the result to T ";
  W>{             " If T>W, while W is always initialized to -1 ";
    T:W];         " Set T to W, and empty the stack ";
  }*
  TW={            " If T==W ";
    U]',*         " Push U and add a ',' between everything in the stack, if there were more than one ";
  }*
  T(              " Push T and decrease by one ";
}/
;                 " Discard the top item, which should be now -1 ";
W                 " Push W ";
':                " Push ':' ";
@                 " Rotate the 3rd item to the top ";

Fiz uma pequena modificação no formato de saída para torná-lo consistente e menos ambíguo, mas não deve ser muito inconveniente.
Jwosty

@ Joshua Não deveria, se isso não é código de golfe.
jimmy23013

Bem, este é o código-golf ... Mas de qualquer maneira, a submissão nice :)
Jwosty

Você pode explicar como isso funciona?
Jerry Jeremias

@JerryJeremiah Editado.
jimmy23013

5

Haskell, 186 bytes

p@(n,s)%(c:z)=maybe((n,s++[c])%z)(\i->p:(n+i,"")%z)$lookup c$zip"),("[-1..1];p%_=[p]
(n,w)&(i,s)|i>n=(i,show i++':':s)|i==n=(n,w++',':s);p&_=p
main=interact$snd.foldl(&)(0,"").((0,"")%)

Programa completo, assume árvore stdin, produz formato de saída especificado em stdout:

& echo '2(7(2,6(5,11)),5(9(4)))' | runhaskell 32557-Deepest.hs 
3:5,11,4

& echo 'A(B(C,D(E)))' | runhaskell 32557-Deepest.hs 
3:E

Guia para o código de golfe (adicionado nomes melhores, assinaturas de tipo, comentários e algumas subexpressões extraídas e nomeadas - mas, caso contrário, o mesmo código; uma versão não-golfista não entraria em conflito com a numeração, nem com a profundidade) com formatação de saída.) :

type Label = String         -- the label on a node
type Node = (Int, Label)    -- the depth of a node, and its label

-- | Break a string into nodes, counting the depth as we go
number :: Node -> String -> [Node]
number node@(n, label) (c:cs) =
    maybe addCharToNode startNewNode $ lookup c adjustTable
  where
    addCharToNode = number (n, label ++ [c]) cs
        -- ^ append current character onto label, and keep numbering rest

    startNewNode adjust = node : number (n + adjust, "") cs
        -- ^ return current node, and the number the rest, adjusting the depth

    adjustTable = zip "),(" [-1..1]
        -- ^ map characters that end node labels onto depth adjustments
        -- Equivalent to [ (')',-1), (',',0), ('(',1) ]

number node _ = [node]      -- default case when there is no more input

-- | Accumulate into the set of deepest nodes, building the formatted output
deepest :: (Int, String) -> Node -> (Int, String)
deepest (m, output) (n, label)
    | n > m     = (n, show n ++ ':' : label)    -- n is deeper tham what we have
    | n == m    = (m, output ++ ',' : label)    -- n is as deep, so add on label
deepest best _ = best                           -- otherwise, not as deep

main' :: IO ()
main' = interact $ getOutput . findDeepest . numberNodes
  where
    numberNodes :: String -> [Node]
    numberNodes = number (0, "")

    findDeepest :: [Node] -> (Int, String)
    findDeepest = foldl deepest (0, "")

    getOutput :: (Int, String) -> String
    getOutput = snd

11
Esse código me aterroriza.
26/06/14

Código explicativo expandido adicionado! Deixe o terror torná-lo mais forte !!
MtnViewMark

Você merece um +1 por isso.
26/06

Oh meu deus, e eu estou lutando com listas: P
Artur Trapp

4

GolfScript (75 caracteres)

Não é especialmente competitivo, mas é suficientemente distorcido para ter algum interesse:

{.48<{"'^"\39}*}%','-)](+0.{;.@.@>-\}:^;@:Z~{2$2$={@@.}*;}:^;Z~\-])':'@','*

O código tem três fases. Primeiramente, nós pré-processamos a string de entrada:

# In regex terms, this is s/([ -\/])/'^\1'/g
{.48<{"'^"\39}*}%
# Remove all commas
','-
# Rotate the ' which was added after the closing ) to the start
)](+

Nós transformamos, por exemplo, A(B(C,D(E)))para 'A'^('B'^('C'^'D'^('E'^)''^)''^). Se atribuirmos um bloco adequado ^, podemos fazer um processamento útil usando ~para avaliar a string.

Em segundo lugar, encontramos a profundidade máxima:

0.
# The block we assign to ^ assumes that the stack is
#   max-depth current-depth string
# It discards the string and updates max-depth
{;.@.@>-\}:^;
@:Z~

Finalmente, selecionamos os nós mais profundos e construímos a saída:

# The block we assign to ^ assumes that the stack is
#   max-depth current-depth string
# If max-depth == current-depth it pushes the string under them on the stack
# Otherwise it discards the string
{2$2$={@@.}*;}:^;
# Eval
Z~
# The stack now contains
#   value1 ... valuen max-depth 0
# Get a positive value for the depth, collect everything into an array, and pop the depth
\-])
# Final rearranging for the desired output
':'@','*

1

Perl 5 - 85

Sinta-se livre para editar este post para corrigir a contagem de caracteres. Uso o sayrecurso, mas não conheço os sinalizadores para executá-lo corretamente sem declarar use 5.010;.

$_=$t=<>,$i=0;$t=$_,$i++while s/\w+(\((?R)(,(?R))?\))?/$1/g,/\w/;@x=$t=~/\w+/gs;say"$i:@x"

Demonstração em ideone

A saída é separada por espaço em vez de separada por vírgula.

O código simplesmente usa regex recursivo para remover a raiz das árvores na floresta, até que não seja possível fazer isso. A sequência anterior ao último conterá todos os nós das folhas no nível mais profundo.

Amostras de execuções

2
0:2

2(3(4(5)),6(7))
3:5

2(7(2,6(5,11)),5(9(4)))
3:5 11 4

1(2(3(4,5),6(7,8)),9(10(11,12),13(14,15)))
3:4 5 7 8 11 12 14 15

1

VB.net

Function FindDeepest(t$) As String
  Dim f As New List(Of String)
  Dim m = 0
  Dim d = 0
  Dim x = ""
  For Each c In t
    Select Case c
      Case ","
        If d = m Then f.Add(x)
        x = ""
      Case "("
        d += 1
        If d > m Then f.Clear() :
        m = d
        x = ""
      Case ")"
        If d = m Then f.Add(x) : x = ""
        d -= 1
      Case Else
        x += c
    End Select
  Next
  Return m & ":" & String.Join(",", f)
End Function

Assunção: valores de nó não pode conter ,, (,)


11
Isso não parece ser um jogo de golfe. Você não pode remover a maior parte desse espaço em branco (não sei o VB)?
26/06/14

Depende que parte do espaço em branco seja significativa.
Adam Speight

1

Javascript (E6) 120

Versão iterativa

m=d=0,n=[''];
prompt().split(/,|(\(|\))/).map(e=>e&&(e=='('?m<++d&&(n[m=d]=''):e==')'?d--:n[d]+=' '+e));
alert(m+':'+n[m])

Ungolfed e testable

F= a=> (
    m=d=0,n=[''],
    a.split(/,|(\(|\))/)
    .map(e=>e && (e=='(' ? m < ++d && (n[m=d]='') : e==')' ? d-- : n[d]+=' '+e)),
    m+':'+n[m]
)

Teste no console do Firefox:

['A', '2(7(2,6(5,11)),5(9(4)))', 'A(B(C,D(E)))']
.map(x => x + ' --> ' + F(x)).join('\n')

Resultado

"A -> 0: A

2 (7 (2,6 (5,11)), 5 (9 (4))) -> 3: 5 11 4

A (B (C, D (E))) -> 3: E "

Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.