我有一个带有以下结构的matlab结构
Tree:
feature : numerical value (= 1)
tru: numerical value (= 2)
gain: numerical value (= 3)
left: struct with left node
right: struct with right node
如何以树的形式打印出来?例如,我想打印出根节点:
node 1 feature 1, tru 2, gain 3
节点2和3分别包含来自left
和right
结构的数据,结构与根节点相同。
我想使用与上面针对节点1描述的格式相同的格式递归打印整个树。
我可以通过
打印我的节点1tree.feature
tree.tru
tree.gain
我无法获得如何以递归方式为所有节点打印其子节点。
答案 0 :(得分:0)
你应该能够拥有像这样的简单递归函数
function printinfo(node)
% Display the details from this node
disp(['Feature: ', num2str(node.feature), ...
'\nTru: ', num2str(node.tru), ...
'\nGain: ', num2str(node.gain)]);
% If any of feature, tru or gain aren't equal to -1, go into left and right
if node.feature ~= -1 || node.tru ~= -1 || node.gain ~= -1
printinfo(node.left)
printinfo(node.right)
end
end
最初使用
调用它printinfo(tree)
然后每个节点调用其各自的right
和left
节点的函数,除非您在评论中描述了停止条件:
当节点功能,tru和gain为-1
时,它将停止