Share my c++ fairly neat and easy dfs solution.


  • 0

    I don't use any global variable, this problem is similar to generate parenthesis.

    class Solution {
    public:
      vector<int> preorderTraversal(TreeNode* root) {
        vector<int> ret;
        dfs(ret, root);
        return ret;
      }
      void dfs(vector<int> &ret, TreeNode *root)
      {
        if (root != NULL)
        {
          ret.push_back(root -> val);
          dfs(ret, root -> left);
          dfs(ret, root -> right);
        }
      }
    };
    

Log in to reply
 

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