二叉树方法实例

时间:2017-12-02 06:06:16

标签: java algorithm tree binary-tree

最近,当我的代码是通用二叉树时,我需要一种方法来对树中所有左子树的值求和,这个方法返回一个整数值。它是一种递归方法,但是当尝试对根值求和时,我无法将T值转换为int,因为它们是不兼容的类型。我创建了一个从二叉树扩展到整数类型的子类,但在这种情况下我需要在我的父类中创建方法,因为递归调用需要在父类中找到methd,这对我来说有点烦人。我认为有一种形式可以避免这种行为。有没有办法避免在我父类中创建方法?

二叉树类:

public class BinaryTree<T> {

protected T root= null;
protected BinaryTree<T> left= null, right= null;

 //All binary tree here

Integer sumLeft() {
    return 0;
}

二叉树整数

public class BinaryTreeInteger extends BinaryTree<Integer> {
//All code here

Integer sumLeft() {
    int suma = 0;       
    if (isLeaf()) {            
        return getRaiz();
    }
    if (left != null) {

            if (!left.EsHoja()) {
                suma += left.getRaiz() + left.sumLeft();
            } else {
                suma += left.sumLeft();
            }              

    }
    if (right != null && !right.isLeaf()) {

            suma += right.sumLeft();                

    }
    return suma;
}

}

}

0 个答案:

没有答案
相关问题