diff --git a/CS notes/pages/Leetcode Binary-Tree-Inorder-Traversal.md b/CS notes/pages/Leetcode Binary-Tree-Inorder-Traversal.md index 3bca0db..13e4d5a 100644 --- a/CS notes/pages/Leetcode Binary-Tree-Inorder-Traversal.md +++ b/CS notes/pages/Leetcode Binary-Tree-Inorder-Traversal.md @@ -94,5 +94,40 @@ public: Iteration ```cpp +/** + * 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 inorderTraversal(TreeNode *root) { + // Iteration + stack pending; + vector answer; + + while (root || !pending.empty()) { + // traverse left first. + while (root) { + pending.push(root); + root = root->left; + } + + root = pending.top(); + pending.pop(); + answer.push_back(root->val); + root = root->right; + } + + return answer; + } +}; ``` \ No newline at end of file