【发布时间】:2016-12-08 17:30:30
【问题描述】:
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);
}
}
}
我想知道为什么迭代版本。无法找到此二叉树中的节点数?它似乎只能找到叶子的数量(如果我对这个说法也有错误,请纠正我)。
【问题讨论】:
-
@xenteros ,请删除重复的标签,它们是完全不同类型的问题。
-
其实完全一样。
-
@xenteros ,您似乎并没有真正浏览整个页面。我不允许使用堆栈,而该页面使用 pop 和 push 功能来计数。我真的很好奇你的判断标准。
标签: java binary-tree