From 0bb4b5d381de7d9e68a5bf22b1bdc780ba40c1f0 Mon Sep 17 00:00:00 2001 From: juan Date: Mon, 4 Jul 2022 16:34:55 +0800 Subject: [PATCH] vault backup: 2022-07-04 16:34:55 --- .../Leetcode Binary-Tree-Inorder-Traversal.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) 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