Video solution | Template sol. for all traversals (Preorder, Inorder, Postorder) | With Examples
Video\nHey everyone i have created a video solution for all DFS traversals (Preorder, Inorder, Postorder) for binary trees, it has a template solution which wil
# Video\nHey everyone i have created a video solution for all DFS traversals (Preorder, Inorder, Postorder) for binary trees, it has a template solution which will help you to implement all the travesals in one go, i have also tried to explain each travesal with a practical example, so that you understand why these traversals are important.\nHere is the video link :\nlanguage used is hindi->\n**Recursive**:\nhttps://www.youtube.com/watch?v=9XJdlw3y4sk\n**Iterative**:\nhttps://youtu.be/iZbG5_gvsJI\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    vector<int> preorderTraversal(TreeNode* root) {\n        stack<TreeNode*> st;\n        vector<int> ans;\n\n        while(!st.empty() || root){\n            while(root){\n                ans.push_back(root->val);\n                st.push(root);\n                root=root->left;\n            }\n            root=st.top();\n            st.pop();\n            root=root->right;\n        }\n        return ans;\n\n        \n        \n    }\n};\n```
['C++']