【问题标题】:How to store each node in a binary search tree in a list?如何将二叉搜索树中的每个节点存储在列表中?
【发布时间】:2017-02-04 16:30:59
【问题描述】:

我正在尝试在二叉搜索树类中编写一个函数,该函数将以public int greater (int n) 的形式返回树中值大于 n 的节点数。我认为将所有值存储在一个列表中然后迭代列表并在每次发现一个数字大于 n 时增加计数可能会更容易。我将如何实施?

到目前为止,这是我的课:

public class BST
{ private BTNode<Integer> root;
    private int count = 0;
    List<Integer> arr = new ArrayList<>();
    private BST right = new BST();
    private BST left = new BST();

    public BST()
  { root = null;
  }

  public boolean find(Integer i)
  { BTNode<Integer> n = root;
    boolean found = false;

    while (n!=null && !found)
    { int comp = i.compareTo(n.data);
      if (comp==0)
        found = true;
      else if (comp<0)
        n = n.left;
      else
        n = n.right;
    }

    return found;
  }

  public boolean insert(Integer i)
  { BTNode<Integer> parent = root, child = root;
    boolean goneLeft = false;

    while (child!=null && i.compareTo(child.data)!=0)
    { parent = child;
      if (i.compareTo(child.data)<0)
      { child = child.left;
        goneLeft = true;
      }
      else
      { child = child.right;
        goneLeft = false;
      }
    }

    if (child!=null)
      return false;  // number already present
    else
    { BTNode<Integer> leaf = new BTNode<Integer>(i);
      if (parent==null) // tree was empty
        root = leaf;
      else if (goneLeft)
        parent.left = leaf;
      else
        parent.right = leaf;
      return true;
    }
  }

  public int greater(int n){ //TODO
      return 0;
  }
}

class BTNode<T>
{ T data;
  BTNode<T> left, right;

  BTNode(T o)
  { data = o; left = right = null;
  }
}

【问题讨论】:

    标签: java list data-structures binary-tree binary-search-tree


    【解决方案1】:

    我不会将列表用作临时存储。

    有一个名为Tree Traversal 的概念允许您访问树的每个节点。

    这是一些伪代码:

    preorder(node)
      if (node = null)
        return
      visit(node)
      preorder(node.left)
      preorder(node.right)
    

    这里的visit 函数在每个节点上只执行一次。 对于像您描述的计数这样的专门遍历,您可以将 visit 替换为您想要的功能,例如:

    if (node.data > n) {
        count += 1
    }
    

    如果你实现一个Preorder 类,你可以扩展它以提供自定义访问功能,那就更好了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      相关资源
      最近更新 更多