---
# System prepended metadata

title: 145. Binary Tree Postorder Traversal
tags: [C++, LeetCode-Medium]

---

# 145. Binary Tree Postorder Traversal
Difficulty: Medium

## Solution

```cpp=
/**
*** Author: R-CO
*** E-mail: daniel1820kobe@gmail.com
*** Date: 2020-11-10
**/
#include <cstdlib>

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
struct TreeNode {
 int val;
 TreeNode *left;
 TreeNode *right;
 TreeNode() : val(0), left(nullptr), right(nullptr) {}
 TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
  vector<int> preorderTraversal(TreeNode* root) {
    vector<int> output;
    preorderTraversal(root, output);
    
    return output;
  }
private:
  void preorderTraversal(TreeNode* node, vector<int> &output) {
    if (node == nullptr) { return; }
    
    output.push_back(node->val);
    preorderTraversal(node->left, output);
    preorderTraversal(node->right, output);
  }
};

int main(int argc, char *argv[]) { return EXIT_SUCCESS; }

```

## Result
Success
Details 
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Binary Tree Preorder Traversal.
Memory Usage: 8.9 MB, less than 5.36% of C++ online submissions for Binary Tree Preorder Traversal.

###### tags: `LeetCode-Medium` `C++`
