✅A Classic Approach to Preorder Tree Traversal: A Recursive Solution | Beats 100% Time [C#]✅
The PreorderTraversal function is the public interface for the algorithm, and it accepts the root node of a binary tree as an argument. It creates an empty list
The PreorderTraversal function is the public interface for the algorithm, and it accepts the root node of a binary tree as an argument. It creates an empty list to store the result of the traversal, and then calls the PreorderTraversalRecursive function on the root node to perform the actual traversal.\n\nThe PreorderTraversalRecursive function has the following steps:\n\nIf the node is null, it returns immediately.\nIt adds the value of the node (node.val) to the list.\nIt calls itself recursively on the left child of the node (node.left).\nIt calls itself recursively on the right child of the node (node.right).\nThis way, the function traverses the tree in a depth-first fashion, visiting the root node first, then the left subtree, and finally the right subtree.\n\nWhen the traversal is complete, the PreorderTraversal function returns the list containing the values of the nodes in the order they were visited.\n\n# Approach\nDFS\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution\n{\n    public IList<int> PreorderTraversal(TreeNode root)\n    {\n        var list = new List<int>();\n        PreorderTraversalRecursive(root, list);\n        return list;\n    }\n\n    private void PreorderTraversalRecursive(TreeNode node, List<int> list)\n    {\n        if (node == null) return;\n        list.Add(node.val);\n        PreorderTraversalRecursive(node.left, list);\n        PreorderTraversalRecursive(node.right, list);\n    }\n}\n```\n\nIf you found my solution helpful, please consider upvoting it to let others know!
['C#']