From 2149af648314814fba1d5226ad2910b0d81ef4e5 Mon Sep 17 00:00:00 2001 From: juan Date: Mon, 4 Jul 2022 15:32:45 +0800 Subject: [PATCH] vault backup: 2022-07-04 15:32:45 --- Leetcode Binary-Tree-Preorder-Traversal.md | 45 ++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/Leetcode Binary-Tree-Preorder-Traversal.md b/Leetcode Binary-Tree-Preorder-Traversal.md index dea90eb..e9edae2 100644 --- a/Leetcode Binary-Tree-Preorder-Traversal.md +++ b/Leetcode Binary-Tree-Preorder-Traversal.md @@ -59,7 +59,52 @@ Preorder, means root is at the "Pre" position, so the order is: The recursion version is easy to implement. +Use Stacks for the iteration method, because stacks are FILO, the **subtree will get traversed first.** +And remember to push **right subtree** first, so that the left one will be traversed first. + + ### Solution +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 preorderTraversal(TreeNode *root) { + if (!root) { + return {}; + } + + // Using stacks, since FILO, the latest gets served first. + vector answer; + stack pending; + + do { + if (root != nullptr) { + answer.push_back(root->val); + // nothing gets pushed if is nullptr; + pending.push(root->right); + pending.push(root->left); + } + root = pending.top(); + pending.pop(); + } while (root || !pending.empty()); + + return answer; + } +}; + +``` Recursion, using private funcs: ```cpp /**