From 7362c5558569d863046478fedd5ce3c40da29bf3 Mon Sep 17 00:00:00 2001 From: juan Date: Mon, 4 Jul 2022 15:08:23 +0800 Subject: [PATCH] vault backup: 2022-07-04 15:08:23 --- Leetcode Binary-Tree-Preorder-Traversal.md | 38 +++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/Leetcode Binary-Tree-Preorder-Traversal.md b/Leetcode Binary-Tree-Preorder-Traversal.md index fe7d114..dea90eb 100644 --- a/Leetcode Binary-Tree-Preorder-Traversal.md +++ b/Leetcode Binary-Tree-Preorder-Traversal.md @@ -56,9 +56,45 @@ 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, using private funcs: +```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) { + // Use two functions: + vector answer; + preorder(root, answer); + return answer; + } + +private: + void preorder(TreeNode *root, vector &answer) { + if (root == nullptr) { + return; + } + + answer.push_back(root->val); + preorder(root->left, answer); + preorder(root->right, answer); + } +}; +``` Recursion: ```cpp @@ -96,4 +132,4 @@ public: } }; -``` \ No newline at end of file +```