ridoy
Programmer
- May 3, 2013
- 6
I am new in Prolog,working with trees such as forming a tree,counting nodes etc.I had done those,face problems when i am trying to apply DFS search to find a node.
Below is my code so far..
When i test it it gives output like..
?- constructTree(T),count_nodes(T,N).
T = tree(1, tree(2, tree(3, nil, nil), tree(4, nil, nil)), tree(5, tree(6, nil, nil), tree(7, nil, nil))),
N = 7.(total node number)
So how can i modify it for searching a node in DFS? Suppose,i want to search node 5 and count iteration number needs to find that node,finally N will print that count number.
Below is my code so far..
Code:
constructTree(tree(1,
tree(2,
tree(3,nil,nil),
tree(4,nil,nil)),
tree(5,
tree(6,nil,nil),
tree(7,nil,nil))
)
).
count_nodes(nil,0).
count_nodes(tree(_,L,R),N):-
count_nodes(L,CL),
count_nodes(R,CR),
N is CL+CR+1.
?- constructTree(T),count_nodes(T,N).
T = tree(1, tree(2, tree(3, nil, nil), tree(4, nil, nil)), tree(5, tree(6, nil, nil), tree(7, nil, nil))),
N = 7.(total node number)
So how can i modify it for searching a node in DFS? Suppose,i want to search node 5 and count iteration number needs to find that node,finally N will print that count number.