Size of a binary tree with non recursive method Java -
hello i'm trying write non recursive method getting size of node since recursion in java expensive. include number of child nodes + 1 (itself). i've converted c implementation how can number of leaf nodes in binary tree non-recursively? in java it's not correct.
edit: algorithm counting size of binary tree, non recursively.
public int size(node n) { stack<node> sizestack = new stack(); int count = 1;//includes 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 counting leaf nodes. own wish count all nodes. algorithm counting leaf nodes adds counter when pops leaf node, , that's true both java , c. program - not problem have defined.
in order count nodes, have increment counter every time pop node stack. means have push nodes, rather loop way have leaf nodes.
if want save on push operations (which reason why algorithm better recursion, unless tree unbalanced towards right) should increment counter every node examining, keep basic loop was.
public int size(node n) { stack<node> sizestack = new stack(); int count = 1;//includes 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; }
Comments
Post a Comment