Advertisement
Guest User

Untitled

a guest
Jan 11th, 2024
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. struct TreeNode {
  7.   int val;
  8.   TreeNode *left;
  9.   TreeNode *right;
  10.   TreeNode() : val(0), left(nullptr), right(nullptr) {}
  11.   TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  12.   TreeNode(int x, TreeNode *left, TreeNode *right)
  13.       : val(x), left(left), right(right) {}
  14. };
  15.  
  16. class Solution {
  17.  
  18. public:
  19.   void dfs(const TreeNode *root, vector<int> &res) {
  20.     if (root == nullptr)
  21.       return;
  22.     dfs(root->left, res);
  23.     res.push_back(root->val);
  24.     dfs(root->right, res);
  25.   }
  26.  
  27.   vector<int> inorderTraversal(TreeNode *root) {
  28.     vector<int> res;
  29.     dfs(root, res);
  30.     return res;
  31.   }
  32. };
  33.  
  34. int main(void) {
  35.   TreeNode *root = new TreeNode(1);
  36.   root->right = new TreeNode(2);
  37.   root->right->left = new TreeNode(3);
  38.   for (const auto &i : Solution().inorderTraversal(root)) {
  39.     cout << i << endl;
  40.   }
  41.   return 0;
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement