简体   繁体   English

预订和反向预订二叉树遍历

[英]Preorder and Reverse Preorder Binary Tree Traversals

I'm trying to recursively call my Preorder and Reverse Preorder methods. 我试图以递归方式调用我的Preorder和Reverse Preorder方法。 The methods work over a array-based binary tree, they are supposed to return the length of all the elements of a subtree. 这些方法适用于基于数组的二叉树,它们应该返回子树的所有元素的长度。 But they do is return the length of the first element of the subtree. 但它们确实返回子树的第一个元素的长度。 If anyone can help it'd be appreciated. 如果有人可以提供帮助,我们将不胜感激。

int left_width(vector<string>& vec, int i, int ret) {
    int left = i * 2 + 1;
    int right = i * 2 + 2;
    ret = ret + vec[i].length();
    if (left < (int)vec.size() && right <= (int)vec.size()) {
            left_width(vec, left, ret);
            left_width(vec, right, ret);
    }
    return ret;

} }

int right_width(vector<string>& vec, int i, int ret) {
    int right = i * 2 + 2;
    int left = i * 2 + 1;
    ret = ret + vec[i].length();
    if (left < (int)vec.size() && right <= (int)vec.size()) {
            right_width(vec, right, ret);
            right_width(vec, left, ret);
    }
    return ret;

} }

If I understood what you're doing correctly, you need to capture the return values from your calls to left_width or right_width to pass along, so you accumulate across all calls. 如果我理解你正在做什么,你需要从你的left_widthright_width调用中获取返回值,以便在所有调用中累积。 For example: 例如:

int right_width(vector<string>& vec, int i, int ret) {
    int right = i * 2 + 2;
    int left = i * 2 + 1;
    ret = ret + vec[i].length();
    if (left < (int)vec.size() && right <= (int)vec.size()) {
        ret = right_width(vec, right, ret);
        ret = right_width(vec, left, ret);
    }
    return ret;
}

Of course, passing a "continuing return value" in as an argument to thread it through the computation really isn't idiomatic recursion. 当然,将“持续返回值”作为参数传递给通过计算的线程实际上并不是惯用的递归。 Usually you do something more like this: 通常你会做更像这样的事情:

int right_width(vector<string>& vec, int i) {
    int right = i * 2 + 2;
    int left = i * 2 + 1;
    int ret = vec[i].length();
    if (left < (int)vec.size() && right <= (int)vec.size()) {
        ret += right_width(vec, right);
        ret += right_width(vec, left);
    }
    return ret;
}

Here, you just sum up all the return values from the recursive calls, along with your own local value, and return it back to the caller. 在这里,您只需将递归调用的所有返回值与您自己的本地值相加,然后将其返回给调用者。 No need to pass the work-in-progress counts down to the callees. 无需将正在进行的工作计数传递给被调用者。

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

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