Size of a binary tree with non recursive method Java

后端 未结 2 1771
野趣味
野趣味 2020-12-12 06:09

Hello I\'m trying to write a non recursive method for getting the size of a node since recursion in Java is expensive. This would include the number of child nodes + 1 (itse

2条回答
  •  情深已故
    2020-12-12 06:24

    Here is a C implementation. RealSkeptic's method above was not that intuitive to me. I provide comments and it should be pretty easy to follow.

    int sizeOfBsTree_nonRec(TreeNode *root)
    {
        if (root == NULL) {
            return 0;
        }
    
        int size = 0;
        Stack S;
        initializeStack(&S);
    
        // Push to the stack all Nodes in the (sub)tree and
        // increase the counter when you pop one out
        push(root, &S);
        while(!isStackEmpty(&S)){
            root = pop(&S);
            size++;
    
            if (root->right != NULL)
                push(root->right, &S);
            if (root->left != NULL)
                push(root->left, &S);
        }
    
        return size;
    }
    

提交回复
热议问题