Non-recusion version in C++


  • 0
    D
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    #include <stack>
    using namespace std;
    
    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode* root) {
            vector<int> list;
            if (root == NULL) {
                return list;
            }
            stack <TreeNode*> stack;
            stack.push(root);
            TreeNode* node;
            
            while (!stack.empty()) {
                node = stack.top();
                stack.pop();
                
                list.push_back(node->val);
                if (node->right != NULL) {
                    stack.push(node->right);
                }
                
                if (node->left != NULL) {
                    stack.push(node->left);
                }
                
            }
            return list;
        }
    };

Log in to reply
 

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