简体   繁体   English

二叉树预序

[英]Binary tree preorder

My preorder method don't work from main, but array elem has been formed rightly (I checked it with printing every step).我的预购方法在 main 中不起作用,但数组元素已经正确形成(我通过打印每一步来检查它)。 All functions/methods used in definition work correctly.定义中使用的所有函数/方法都可以正常工作。 I think the problem occurs because of line "return elem;".我认为问题的发生是因为行“return elem;”。 Can anyone suggest any idea, it's too important.任何人都可以提出任何想法,这太重要了。

T* TreeNode<T>::preorder()const 
{
    T* elem = new T[elCount(left)+elCount(right)+1];
    elem[0] = data;
    TreeNode<T>* curr = left;
    Stack<TreeNode<T>*> st;
    if (right) {
        st.push(right);
    }
    int i = 1;
    while (curr) {
        elem[i++] = curr->getData();
        //std::cout << elem[i - 1];
        
        if (curr->getRight()) 
            st.push(curr->getRight());
        
        curr = curr->getLeft();
        if (!curr) 
        {
            curr = st.getTop();
            st.pop();
        }   }
    return elem;
}

It's a bit difficult to see exactly what you're trying to do as it wasn't specified, but it seems that you're trying to grab all the data from your binary tree.由于未指定,因此很难确切地看到您正在尝试做什么,但您似乎正在尝试从二叉树中获取所有数据。 This GFG article does a really simple explanation and breakdown of how to transverse a binary tree. 这篇 GFG 文章对如何遍历二叉树做了一个非常简单的解释和分解。 Obviously your nodes are more complicated, but the general logic is the same.显然你的节点更复杂,但大体逻辑是一样的。 I'd ask yourself as to whether the preorder() function really needs to be part of the tree node class and if a separate function wouldn't be a bit more useful.我会问自己preorder() function 是否真的需要成为树节点 class 的一部分,如果一个单独的 function 不会更有用一点。 I'd also consider using a std::vector rather than the carray you're currently using.我还会考虑使用std::vector而不是您当前使用的 carray。 If you need the fixed size, std::array would probably also work better.如果您需要固定大小, std::array也可能会更好。

To show how you could possibly rewrite your code you can try something like为了展示你如何重写你的代码,你可以尝试类似的东西

std::vector<int> vect;

template<class T>
void preorder(const TreeNode<T>& node, vector<T>& elem) {
    if(!node.getData()) {
        return;
    }

    elem.push(node.getData());

    if(node.getLeft()) {
        preorder(node.getLeft());
    }

    if(node.getRight()) {
        preorder(node.getRight());
    }
}

This isn't perfect as I wrote this off the top of my head, but it should provide an easy groundwork for traversing the binary tree and pulling out all the data.这并不完美,因为我在脑海中写下了这个,但它应该为遍历二叉树和提取所有数据提供一个简单的基础。 A little bit of recursion should make it a lot easier.一点递归应该会使它更容易。

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

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