Cpp code with a stack


  • 1
    N
    class Solution {
    public:
        vector<int> inorderTraversal(TreeNode* root) {
            vector<int> inordervals;
            stack<TreeNode*> Tree;
            if(!root){
                return inordervals;
            }
            bool flag = 0;
            Tree.push(root);
            while(!Tree.empty()){
                TreeNode* ThisNode = Tree.top();
                if(ThisNode->left && !flag){
                    Tree.push(ThisNode->left);
                }
                else{
                    inordervals.push_back(ThisNode->val);
                    Tree.pop();
                    if(ThisNode->right){
                        Tree.push(ThisNode->right);
                        flag=0;
                    }
                    else{
                        flag=1;
                    }
                }
            }
            return inordervals;
        }
    };

Log in to reply
 

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