Is there any optimization of mine Binary Tree Inorder Traversal iteratively solution?


  • 0
    N

    I think below code is not efficiently, but I cannot find where can get optimizaiton.
    Can someone help point out? Thanks.

    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> res;
        stack<TreeNode*> tree;
        if(root == NULL)
            return res;
        tree.push(root);
        TreeNode* node = root;
        while(!tree.empty()){
            if(node->left != NULL){
                tree.push(node->left);
                node = node->left;
            }
            else if(node->right != NULL){
                res.push_back(tree.top()->val);
                tree.pop();
                tree.push(node->right);
                node = node->right;
            }
            else{
                res.push_back(tree.top()->val);
                tree.pop();
                if(!tree.empty()){
                    node = tree.top();
                    node->left = NULL;
                }
            }
         }
         return res;
    }

Log in to reply
 

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