C++ solution, short, intelligible, but destroy the tree


  • 0
    1
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> stk;
        if(!root) return result;
        stk.push(root);
        while(!stk.empty()){
            auto ptr=stk.top();
            stk.pop();
            if(!ptr->left and !ptr->right)
                result.push_back(ptr->val);
            else{
                if(ptr->right){
                    stk.push(ptr->right);
                    ptr->right=NULL;
                }
                stk.push(ptr);
                if(ptr->left){
                    stk.push(ptr->left);
                    ptr->left=NULL;
                }
            }
        }
        return result;
    }

Log in to reply
 

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