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.
1function TreeNode(val, left, right) {
2 this.val = (val===undefined ? 0 : val);
3 this.left = (left===undefined ? null : left);
4 this.right = (right===undefined ? null : right);
5}
6
7var tree2str = function(t) {
8 if (!t) return "";
9
10 let result = t.val.toString();
11 if (t.left || t.right) {
12 result += '(' + tree2str(t.left) + ')';
13 }
14 if (t.right) {
15 result += '(' + tree2str(t.right) + ')';
16 }
17 return result;
18};
The JavaScript solution is implemented as a function tree2str
. Like other solutions, it recursively builds the string from the root node's value, including child nodes within parentheses. The conditional checks ensure that the right structure is maintained with or without left children.
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.