简体   繁体   English

树遍历-有序位置

[英]Tree traversal - inorder position

I am trying to find the value of the kth node in tree, using recursive in order traversal. 我试图使用递归顺序遍历在树中找到kth节点的值。

The code below is done with recursion, but my implementation is way too slow. 下面的代码是通过递归完成的,但是我的实现太慢了。

Can someone please give me a hint how to make it faster? 有人可以给我提示如何使其更快吗? ( reihe and pos are class variables, they both start from 0, and I save the final result in pos ). reihepos是类变量,它们都从0开始,我将最终结果保存在pos )。

Here is what I have done so far, and any help would be really appreciated: 这是我到目前为止所做的,任何帮助将不胜感激:

void valueAtPosition(int k) {

            if(this.left!=null){
                left.valueAtPosition(k);
            }
            if(reihe++==k){
                pos=this.elem;

            }

           else if(this.right!=null){
                right.valueAtPosition(k);
            }
        }

To remove the need for reihe (and I'm assuming it's not english since it makes no sense as a variable name to me). 为了消除对reihe的需要(我假设它不是英语,因为它对我来说是一个变量名称,没有意义)。 I've passed the variable k as a return value. 我已经将变量k作为返回值传递了。 When it reaches 0, I return the current value and stop searching. 当它达到0时,我返回当前值并停止搜索。

int valueAtPosition(int k) {

    if(this.left!=null k >= 0){
        k = left.valueAtPosition(k);
    }

    if(k == 0){
        pos=this.elem;
    }
    k--;

    if(this.right!=null && k > 0){
        k = right.valueAtPosition();
    }

    return k;
}

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

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