Try   HackMD

94. Binary Tree Inorder Traversal

Solution - Recursion
/** * 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) {} * }; */ class Solution { private: vector<int> res; public: vector<int> inorderTraversal(TreeNode* root) { dfs(root); return res; } void dfs(TreeNode* root) { if(!root) return; dfs(root->left); res.push_back(root->val); dfs(root->right); } };
  • T:
    O(N)
  • S:
    O(N)
Hint - Iteration
/** * 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) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode* root) { // Stack to help with traversal // Vector to store the result of the inorder traversal // Start with the root node // Traverse the tree // Continue until all nodes are processed while () { // Reach the leftmost node of the current node while () { // Push the current node onto the stack // Move to the left child } // Process the node // Get the node from the top of the stack // Remove the node from the stack // Add the node's value to the result // Move to the right child of the node } // Return the vector containing the inorder traversal } };
Solution - Iteration
/** * 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) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode* root) { stack<TreeNode*> stk; vector<int> res; TreeNode* node = root; while (node || !stk.empty()) { while (node) { stk.push(node); node = node->left; } node = stk.top(); stk.pop(); res.push_back(node->val); node = node->right; } return res; } };
  • T:
    O(N)
  • S:
    O(N)