Sponsored
Sponsored
This approach uses a recursive depth-first traversal starting from the root. For each node, construct the string representation by first adding the node's value. Then recursively obtain the string for the left and right subtrees. Handle empty parentheses carefully to meet problem constraints, particularly when a node has a right child but no left child.
Time Complexity: O(n), where n is the number of nodes in the tree, as each node is visited once.
Space Complexity: O(h), where h is the height of the tree, due to the recursive call stack.
1#include <string>
2struct TreeNode {
3 int val;
4 TreeNode *left;
5 TreeNode *right;
6 TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
7};
8
9class Solution {
10public:
11 std::string tree2str(TreeNode* t) {
12 if (!t) return "";
13
14 std::string result = std::to_string(t->val);
15 if (t->left || t->right) {
16 result += '(' + tree2str(t->left) + ')';
17 }
18 if (t->right) {
19 result += '(' + tree2str(t->right) + ')';
20 }
21 return result;
22 }
23};
The C++ solution uses class Solution
with a method tree2str
. It recursively constructs strings for left and right subtrees. It ensures that empty parentheses are included only when needed. Preorder traversal ensures that the node value is processed before its children, aligning with the requirements.
This approach leverages an iterative traversal using a stack to emulate the recursive call stack. This can be beneficial in languages without native recursion optimization or for learning alternative tree traversal methods. The stack helps manage nodes and their parents as we build the string representation iteratively.
Time Complexity: O(n)
Space Complexity: O(n), as the stack can store every node.
1class TreeNode:
2 def __init__(self, val=0, left=None,
The iterative Python solution uses a stack to manage tree traversal and construct the string. Each node's value is appended as we pop it from the stack. Special handling ensures proper insertion of parentheses to reflect tree structure accurately without recursion.