求一个java二叉树计算节点总数的方法~

2024-12-02 11:16:27
推荐回答(3个)
回答1:

用递归:

public int size(){
return size(root);
}

public int size(TreeNode root){
if(root==null) return 0;
else return 1+size(root.left)+size(root.right);
}

不懂百度hi我。

回答2:

public int size(Root r)
{
int i = 1;
if(r.left != null)
{
i += (size(r.left) + 1);
}
if(r.right != null)
{
i += (size(r.right) + 1);
}
return i;
}

没测试过 不知大对不对 凭脑袋写的~

回答3:

//递归版本
@Override
public int size() {
return size(root);
}

private int size(BinaryTreeNode element) {
if (element == null) {
return 0;
} else {
return size(element.getlChild()) + size(element.getrChild()) + 1;
}
}
//迭代版本
@Override
public int size() {
int node = 0;
if (root == null)
return node;
Stack> stack1 = new Stack<>();
Stack> stack2 = new Stack<>();
stack1.push(root);
while(!stack1.isEmpty()){
BinaryTreeNode current = stack1.pop();
stack2.push(current);
if (current.getlChild()!=null) {
stack1.push(current.getlChild());
}
if (current.getrChild()!=null) {
stack1.push(current.getrChild());
}
}
while (!stack2.isEmpty()) {
stack2.pop();
node++;
}
return node;
}