Let's say I have a list of branches, how to find a list of tree list that are singly connected together? The below diagram should illustrate my point. The input is a list of branches in a single tree, as labeled, ie. 1
, 2
, 3
and so on
views:
48answers:
2
+1
A:
The process is as follows:
- Create a function that accepts a tree node as a parameter
- If the node has no children, print the value of the current node and return.
- If the node has two children, end the current list of single node values, then recurse into the left node, then the right node
- If the node has one child, add it to the list of values contained in the tree, then recurse into that node.
- Continue.
Kyle Rozendo
2010-04-22 07:00:25
@What if a node has more than two children?
Ngu Soon Hui
2010-04-22 07:01:32
@Ngu - It shouldn't though? Sorry, I'm assuming by your image that this is a binary tree?
Kyle Rozendo
2010-04-22 07:03:28
@Kyle, it's not binary; as can be seen from tree `5`,`6`,`7`,`8`
Ngu Soon Hui
2010-04-22 07:06:16
Define "right node", for a tree with 3 children. Seems we're not dealing with binary trees here.
cHao
2010-04-22 07:06:58
@Ngu , @cHao - What one could do is follow the same process, however you'll have to enumerate the children if the amount of children is: `> 1`.
Kyle Rozendo
2010-04-22 07:10:51
+1
A:
According to image, there is a really simple solution. Let's make a list, with elements, that are lists of the same type. Procedure will be called tree_lists(list, tree). All you need to do is:
- Looking at current joint, you have your list pointer on the first element of list.
- If there are
more than one child in current node: iterate through each
subtree, incrementing list pointer
and calling
tree_lists(list[i],current_subtree) where i is list pointer and current_subtree is current subtree =) - If ony one child exists, just add this joint to the current list item and move on to next.
- Of course, list pointer and list values must be somehow global and modified in recurion as well.
Anton
2010-04-22 07:19:18