java 非递归求二叉树高度,使用非递归方法Java的二叉树的大小

Hello I'm trying to write a non recursive method for getting the size of a node since recursion in Java is expensive. This would include the number of child nodes + 1 (itself). I've converted an C implementation How can I get number of leaf nodes in binary tree non-recursively? in to Java but it's not correct.

Edit: algorithm for counting the size of binary tree, non recursively.

public int size(Node n) {

Stack sizeStack = new Stack();

int count = 1;//includes the n node

if(n == null) {

return 0;

}

sizeStack.push(n);

while(!sizeStack.isEmpty()){

node = sizeStack.pop();

while(node != null) {

count++;

if(node.right != null){

sizeStack.push(node.right);

}

node = node.left;

}

}

return count;

}

解决方案

Your algorithm is counting leaf nodes. Your own wish was to count all the nodes. An algorithm for counting leaf nodes only adds to the counter when it pops a leaf node, and that's true both for Java and for C. So actually your program is good - but not for the problem you have defined.

In order to count all the nodes, you have to increment the counter every time you pop a node from the stack. This means you have to push all the nodes, rather than loop the way you have for the leaf nodes.

If you want to save on push operations (which is the only reason why this algorithm will be better than recursion, unless the tree is unbalanced towards the right) you should just increment the counter for every node that you are examining, but keep the basic loop as it was.

public int size(Node n) {

Stack sizeStack = new Stack();

int count = 1;//includes the n node

if(n == null) {

return 0;

}

sizeStack.push(n);

while(!sizeStack.isEmpty()){

node = sizeStack.pop();

while(node != null) {

count++;

if(node.right != null){

sizeStack.push(node.right);

}

node = node.left;

}

}

return count;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值