0ms easy solution for beginners


  • 0
    V

    Start off traversing all left subtree and print then push to stack as you go until you hit null. Then you want to start popping off nodes, each time you pop off a node you want to check if it has a right subtree. If it does then you set the root equal to the right and repeat the process.

    vector<int> preorderTraversal(TreeNode* root) {
        if (!root) return vector<int>();
        vector<int> res;
        stack<TreeNode*> s;
        
        while(1){
            while(root){
                res.push_back(root->val); 
                s.push(root); 
                root = root->left; 
            }
            if (!s.empty()){
                if (s.top()->right){
                    root = s.top()->right; 
                }
                s.pop();
            }
            else break;
        }
        
        return res;
    }

Log in to reply
 

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