Leetcode 144. Binary Tree Preorder Traversal
Leetcode Problem 144: Binary Tree Preorder Traversal
Given the root of a binary tree, return the preorder traversal of its nodes’ values.
In preorder traversal, the nodes are recursively visited in this order:
Input: root = [1,null,2,3]
Output: [1,2,3]
0 <= Number of nodes <= 5000) and node values (usually within a variety of integer ranges).Let’s implement the preorder traversal using a recursive approach.
#include <vector>
using namespace std;
// 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:
void preorderTraversalHelper(TreeNode* node, vector<int>& traversal) {
if (node == nullptr) {
return;
}
traversal.push_back(node->val); // Visit the root
preorderTraversalHelper(node->left, traversal); // Traverse left subtree
preorderTraversalHelper(node->right, traversal); // Traverse right subtree
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
preorderTraversalHelper(root, result);
return result;
}
};
preorderTraversalHelper that takes the current node and the traversal list as its arguments.nullptr, return immediately because there is nothing to process.preorderTraversal function, initialize an empty vector and call the helper function starting with the root.O(n), where n is the number of nodes in the binary tree. Each node is visited exactly once.O(n) in the worst case for the recursion stack, where the tree is skewed and has a height of n. In the average case (balanced tree), the recursion stack will have depth O(log n). Additionally, the space required for the output list is O(n).This solution ensures that every node is processed efficiently following the preorder traversal order: root, left, right.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?