C++ implementation using recursion


  • 0
    T
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    private:
        void preorderTraversalHelper(TreeNode* root, vector<int> &result)
        {
            if(!root)
                return;
            result.push_back(root->val);
            if(root->left)
                preorderTraversalHelper(root->left, result);
            if(root->right)
                preorderTraversalHelper(root->right, result);
        }
    public:
        vector<int> preorderTraversal(TreeNode* root) {
            vector<int> result;
            preorderTraversalHelper(root, result);
            return result;
        }
    };

Log in to reply
 

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