简体   繁体   English

在二进制搜索树中查找落入范围内的数据值,并以升序打印

[英]find data values that falls in range in a binary search tree and print them out in ascending order

This is a homework assignment. 这是一项家庭作业。 I need to recursively traverse through a binary search tree, to find out if a node's data value falls in a range (inclusive), and print them out in ascending order. 我需要递归地遍历二叉搜索树,以找出节点的数据值是否在一个范围内(包括端点),并以升序打印出来。

My thought process goes: To print the data value out in ascending order, I need to do in-order traversal on the search tree. 我的思考过程是:为了按升序打印数据值,我需要在搜索树中进行有序遍历。 To traverse efficiently, if a node's left child is less than the lower value, and the node's data is less than the lower value, the program should stop traverse to the left. 为了有效遍历,如果节点的左孩子小于下限值,并且节点的数据小于下限值,则程序应停止向左遍历。 On the same token, if a node's right child is larger than the upper value, and the node's data is more than the upper value, the program should stop traverse to the right. 同样,如果节点的右子节点大于上限值,并且节点的数据大于上限值,则程序应停止向右遍历。

So here goes my implementation, with error: 因此,我的实现出现了错误:

public void rangeSearch(int lower, int upper) {
    if (lower > upper)
        throw new IllegalArgumentException("lower > upper");

    if (root != null)
        rangeSearchTree(root, lower, upper);
}

private static void rangeSearchTree(Node root, int lower, int upper) {
    Node leftChild = root.left;
    Node rightChild = root.right;
    if (leftChild != null && root.key > lower) {
        root = leftChild;
        rangeSearchTree(root, lower, upper);
    } 
    if (root.key >= lower && root.key <= upper) {
        System.out.print(root.key + " ");
    } 
    if (rightChild != null && root.key < upper) {
        root = rightChild;
        rangeSearchTree(root, lower, upper);
    }
}

The tree has structure of: 该树具有以下结构:

      7
     / \
    5   9
   / \ / 
  2  6 8
   \
    4

When I enter 6 for lower bound value and 9 for upper bound value, I get 6 8 8 . 当我为下限值输入6并为上限值输入9 ,我得到6 8 8 The correct answer should be 6 7 8 9 . 正确答案应该是6 7 8 9 Any suggestions? 有什么建议么?

if (leftChild != null && root.key > lower) {
    root = leftChild;  <---- Gotcha!
    rangeSearchTree(root, lower, upper);
} 
if (root.key >= lower && root.key <= upper) {

You are changing the root in the middle of the code. 您正在更改代码中间的root The root that you evaluate in the second if is not the one passed as a parameter but its left child... 您在第二个if评估的root不是作为参数传递的root ,而是它的左子节点...

如果第二个成为第一个,我认为应该解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM