s=struct('parent',{'A','B','C','D','E','F','G'},'children',{'BC','DE','F','G','','',''})
function [nodesnum]=numofnodes(s,num,node)%s为树的结构体,node为子树的根节点
syms A
for i=1:size(s,2)
if isequal(s(i).parent,node)
t=i
end
end
if isempty(s(t).children)
num=num
else
A=s(t).children
num=size(A,2)+num
end
for j=1:size(A,2)
for k=t:size(s,2)
if isequal(s(k).parent,A(j))
numofnodes(s,num,s(k).parent)
end
end
end
上面的程序是求树的节点数,求高手给我看看为什么出来的结果不正确,谢谢大家啦!
------解决方案--------------------
楼主,你的数据结构不科学
像你这样的设计,完全可以用2个cell数组保存信息,用struct完全没有意义
例如:
parent = {'A','B','C','D','E','F','G'};
children = {'BC','DE','F','G','','',''};
这样也没什么问题啊,因为你本来想利用struct这个类型来保存树的信息,包括父子节点信息,应该这样
function temp()
clc;
% set the data
G = struct(); G.parent = 'D'; G.children = []; G.name = 'G';
F = struct(); F.parent = 'C'; F.children = []; F.name = 'F';
E = struct(); E.parent = 'B'; E.children = []; E.name = 'E';
D = struct(); D.parent = 'B'; D.children = [G]; D.name = 'D';
C = struct(); C.parent = 'A'; C.children = [F]; C.name = 'C';
B = struct(); B.parent = 'A'; B.children = [D,E]; B.name = 'B';
A = struct(); A.parent = ''; A.children = [B,C]; A.name = 'A';
% get the layer
layer = 0; root = A;
while ~isempty(root.children)
layer = layer+1;
root = root.children(1);
end
% number of nodes
global num; num = 0;
% print tree info
deepFirstPrint(A);
% display info
fprintf('There are %d nodes!\n',num);
end
% sub function for printing
function deepFirstPrint(node)
global num;
num = num+1;
% print self
fprintf('Current:\t%s\nParent:\t\t%s\nChildren:\t',node.name,node.parent);
for i=1:length(node.children)
fprintf('%s ',node.children(i).name);
end
fprintf('\n======================================\n');
% iteratively print children
for i=1:length(node.children)
deepFirstPrint(node.children(i));
end
end
运行结果:
Current: A
Parent:
Children: B C
======================================
Current: B
Parent: A
Children: D E
======================================
Current: D
Parent: B
Children: G
======================================
Current: G
Parent: D
Children:
======================================
Current: E
Parent: B
Children:
======================================
Current: C
Parent: A
Children: F
======================================
Current: F
Parent: C
Children:
======================================
There are 7 nodes!
>>
其实matlab也有class定义,你help class就能看到帮助文档的,虽然不如c++或者java方便,但是好歹也提供了oop的办法,大致定义是这样的
classdef ClassName
methods
function obj = ClassName(arg1,arg2,...)
obj.Prop1 = arg1;
...
end
function normal_method(obj,arg1,...)
...
end
end
methods (Static = true)
function static_method(arg1,...)
...
end
end
end