Help with my run-time error morris traversal code.


  • 0
    class BSTIterator
    {
    private:
    	TreeNode *node = nullptr;
    	void builder(TreeNode *root)
    	{
    		if (root->left == nullptr) return;
    		TreeNode *prev = root->left;
    		while (prev->right && prev->right != root)
    			prev = prev->right;
    		if (prev->right == root)
    			return;
    		prev->right = root;
    		if (root->left)
    			builder(root->left);
    		if (root->right)
    			builder(root->right);
    	}
    public:
    	BSTIterator(TreeNode *root)
    	{
    		if (root == nullptr) return;
    		builder(root);
    		node = root;
    		while (node->left)
    			node = node->left;
    	}
    	bool hasNext()
    	{
    		return node != nullptr;
    	}
    	int next()
    	{
    		int res = node->val;
    		node = node->right;
    		return res;
    	}
    };
    

    I could run on my local machine with visual studio, but it got rte with case [2, 1], pls help!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.