From 5009118bee8c439189958c72e4df834c589f21a7 Mon Sep 17 00:00:00 2001 From: juan Date: Mon, 4 Jul 2022 15:01:29 +0800 Subject: [PATCH] vault backup: 2022-07-04 15:01:29 --- Leetcode Binary-Tree-Preorder-Traversal.md | 99 ++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 Leetcode Binary-Tree-Preorder-Traversal.md diff --git a/Leetcode Binary-Tree-Preorder-Traversal.md b/Leetcode Binary-Tree-Preorder-Traversal.md new file mode 100644 index 0000000..fe7d114 --- /dev/null +++ b/Leetcode Binary-Tree-Preorder-Traversal.md @@ -0,0 +1,99 @@ +# Leetcode Binary-Tree-Preorder-Traversal + +#### 2022-07-04 14:51 + +> ##### Algorithms: +> #algorithm #DFS #DFS_preorder +> ##### Data structures: +> #DS #binary_tree +> ##### Difficulty: +> #coding_problem #difficulty-easy +> ##### Additional tags: +> #leetcode +> ##### Revisions: +> N/A + +##### Related topics: +```expander +tag:# +``` + + + +##### Links: +- [Link to problem](https://leetcode.com/problems/binary-tree-preorder-traversal/) +___ +### Problem +Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. + +#### Examples +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg) + +**Input:** root = [1,null,2,3] +**Output:** [1,2,3] + +**Example 2:** + +**Input:** root = [] +**Output:** [] + +**Example 3:** + +**Input:** root = [1] +**Output:** [1] +#### Constraints +- The number of nodes in the tree is in the range `[0, 100]`. +- `-100 <= Node.val <= 100` +### Thoughts + +> [!summary] +> This is a #binary_tree #DFS_preorder problem. + +Preorder, means root is at the "Pre" position, so the order is: + +- Search root node +- Search left sub-tree +- Search right sub-tree +The recursion version is easy to implement. + +### Solution + +Recursion: +```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 the node is empty + if (root == nullptr) { + return {}; + } + // First check root + vector answer; + + answer.push_back(root->val); + + vector left = preorderTraversal(root->left); + answer.insert(answer.end(), left.begin(), left.end()); + + vector right = preorderTraversal(root->right); + answer.insert(answer.end(), right.begin(), right.end()); + + return answer; + } +}; + +``` \ No newline at end of file