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.
1public class TreeNode {
2 public int val;
3 public TreeNode left;
4 public TreeNode right;
5 public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
6 this.val = val;
7 this.left = left;
8 this.right = right;
9 }
10}
11
12public class Solution {
13 public string Tree2str(TreeNode t) {
14 if (t == null) return "";
15
16 string result = t.val.ToString();
17 if (t.left != null || t.right != null) {
18 result += "(" + Tree2str(t.left) + ")";
19 }
20 if (t.right != null) {
21 result += "(" + Tree2str(t.right) + ")";
22 }
23 return result;
24 }
25}
The C# solution in class Solution
with method Tree2str
recursively traverses the tree nodes. Each node's value is converted to a string, and its children are evaluated to maintain the correct tree format in the output. It manages empty pairs of parentheses as needed for correct structural representation.
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.