Search code examples
c++data-structuresreturnbinary-treepreorder

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). All functions/methods used in definition work correctly. I think the problem occurs because of line "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;
}

Solution

  • 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. 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. I'd also consider using a std::vector rather than the carray you're currently using. If you need the fixed size, std::array would probably also work better.

    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.