二叉树:
Node类有方法:
Node getLeftChild()
Node getRightChild()
int getLeafNumber() (返回该节点下的叶子数目)
int getDepth() (叶子深度是1,向上依次加1)
boolean isleaf()
Tree类有方法:
Node getParent()
Node getRoot()
想得到某个节点左面的所有叶子数目。(比如5叶子的一棵树,第四个叶子左面叶子数目就是3,第四个叶子的父节点左面叶子数目也是3)
请教比较好的逻辑?谢啦
从根开始做一次左遍历,访问到叶子就+1,访问到给定节点就跳出
以下假定tree是你的树,stop_node是某个节点
在高级语言里,如果已经定义了traverse
[code=fake]
n = 0
print tree.traverse ->(node){
return n if node == stop_node
n += 1 if node.leaf?
}
[/code]
若一些的语言,就要写多点
[code=fake]
def count_left node, stop_node = nil
#若有参数2则初始化
static n
static stop
if stop_node
n = 0
stop = stop_node
end
#遍历
if node == stop
throw n
elsif node.leaf?
n++
elsif node
count_left node.left
count_left node.right
end
end
try
count_left tree.root, stop_node
print 'stop_node not in tree'
catch n
#输出结果
print 'left nodes count:' + n
end
[/code]
另外,如果你的树是按照左遍历顺序存储而且可以访问,那就简单多了
如果你的函数非常重量级而且效率很重要,你可能要把递归写成迭代...whatever,that's another story
你那个用递归算法来做,比如说,首先你要定义一个变量用来计算遍历了多少个结点(计算器),我给你一个任意的结点,若其存左孩子,那么你定义的变量就加一,如果不存在你就判断他是否存在右结点,采用的遍历方式是:根---左---右;你参考一下数据结构书吧,代码就四五行,可筒单了,这是我大学时候专业课学的,希望对你有所帮助
是完全二叉树吗?