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.
1class TreeNode {
2 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode(int x) { val = x; }
6}
7
8class Solution {
9 public String tree2str(TreeNode t) {
10 if (t == null) return "";
11
12 String result = t.val + "";
13 if (t.left != null || t.right != null) {
14 result += "(" + tree2str(t.left) + ")";
15 }
16 if (t.right != null) {
17 result += "(" + tree2str(t.right) + ")";
18 }
19 return result;
20 }
21}
The Java solution defines a Solution
class with a method tree2str
. It uses a recursive approach to obtain string representations of left and right children. The inclusion of parentheses is carefully managed to meet the problem's conditions, especially for nodes with a right child but no left child.
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.