二叉树的中序遍历的思想

中序遍历就是将一个二叉树的所有结点按照顺序打印出来(假定这个数的构造是左节点小于父节点,右节点大于父节点)

private void print(Node x) {
   if (x == null) return;
   print(x.left);
   StdOut.println(x.key);
   print(x.right);
}

 

二叉树查找指定范围的操作

    public Iterable<Key> keys() {
        if (isEmpty()) return new Queue<Key>();
        return keys(min(), max());
    }    
    public Iterable<Key> keys(Key lo, Key hi) {
        Queue<Key> queue = new Queue<Key>();
        keys(root, queue, lo, hi);
        return queue;
    } 

    private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { 
        if (x == null) return; 
        int cmplo = lo.compareTo(x.key); 
        int cmphi = hi.compareTo(x.key); 
        if (cmplo < 0) keys(x.left, queue, lo, hi); 
        if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); 
        if (cmphi > 0) keys(x.right, queue, lo, hi); 
    } 

 

posted @ 2021-01-18 10:24  wangheq  阅读(148)  评论(0编辑  收藏  举报