class TreeNode {
TreeNode left;
TreeNode right;
char ch;
TreeNode(char ch){
this.right = null;
this.left = null;
this.ch = ch;
}
TreeNode(TreeNode left, TreeNode right, char ch){
this.left = left;
this.right = right;
this.ch = ch;
}
}
public class ExpressionTree {
public TreeNode root;
public void inorder() {
inorder(root);
}
public void inorder(TreeNode node) {
if (node != null){
inorder(node.left);
System.out.printf(node.ch + " ");
inorder(node.right);
}
}
public void preorder() {
preorder(root);
}
public void preorder(TreeNode node) {
if (node != null){
System.out.printf(node.ch + " ");
preorder(node.left);
preorder(node.right);
}
}
public void postorder() {
postorder(root);
}
public void postorder(TreeNode node) {
if (node != null){
postorder(node.left);
postorder(node.right);
System.out.printf(node.ch + " ");
}
}
public int size() {
int countLeft = 0, countRight= 0;
TreeNode nodeLeft = this.root.left;
TreeNode nodeRight = this.root.right;
if (this.root == null)
return 0;
if (this.root.left == null && this.root.right == null)
return 1;
while (nodeLeft != null){
countLeft = countLeft + 1;
nodeLeft = nodeLeft.left;
}
while (nodeRight != null){
countRight = countRight + 1;
nodeRight = nodeRight.right;
}
return 1 + countLeft + countRight;
}
public int recSize() { return recSize(root); }
public int recSize(TreeNode node) {
int count = 0;
if (node == null)
return 0;
if (node.left == null && node.right == null){
return 1;
}else{
return 1 + recSize(node.left) + recSize(node.right);
}
}
}
I am wondering why the iteration ver. is not working to find the number of node in this binary tree? It seems to be able to find the number of leafs only(Please correct me if i am wrong to this statement also).