|
| 1 | +# 606. Construct String from Binary Tree |
| 2 | + |
| 3 | +- Difficulty: Easy. |
| 4 | +- Related Topics: String, Tree, Depth-First Search, Binary Tree. |
| 5 | +- Similar Questions: Construct Binary Tree from String, Find Duplicate Subtrees. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. |
| 10 | + |
| 11 | +Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. |
| 12 | + |
| 13 | + |
| 14 | +Example 1: |
| 15 | + |
| 16 | + |
| 17 | + |
| 18 | +``` |
| 19 | +Input: root = [1,2,3,4] |
| 20 | +Output: "1(2(4))(3)" |
| 21 | +Explanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)" |
| 22 | +``` |
| 23 | + |
| 24 | +Example 2: |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | +``` |
| 29 | +Input: root = [1,2,3,null,4] |
| 30 | +Output: "1(2()(4))(3)" |
| 31 | +Explanation: Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output. |
| 32 | +``` |
| 33 | + |
| 34 | + |
| 35 | +**Constraints:** |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | +- The number of nodes in the tree is in the range `[1, 104]`. |
| 40 | + |
| 41 | +- `-1000 <= Node.val <= 1000` |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +## Solution |
| 46 | + |
| 47 | +```javascript |
| 48 | +/** |
| 49 | + * Definition for a binary tree node. |
| 50 | + * function TreeNode(val, left, right) { |
| 51 | + * this.val = (val===undefined ? 0 : val) |
| 52 | + * this.left = (left===undefined ? null : left) |
| 53 | + * this.right = (right===undefined ? null : right) |
| 54 | + * } |
| 55 | + */ |
| 56 | +/** |
| 57 | + * @param {TreeNode} root |
| 58 | + * @return {string} |
| 59 | + */ |
| 60 | +var tree2str = function(root) { |
| 61 | + if (!root) return ''; |
| 62 | + var res = `${root.val}`; |
| 63 | + if (root.left || root.right) res += `(${tree2str(root.left)})`; |
| 64 | + if (root.right) res += `(${tree2str(root.right)})`; |
| 65 | + return res; |
| 66 | +}; |
| 67 | +``` |
| 68 | + |
| 69 | +**Explain:** |
| 70 | + |
| 71 | +nope. |
| 72 | + |
| 73 | +**Complexity:** |
| 74 | + |
| 75 | +* Time complexity : O(n). |
| 76 | +* Space complexity : O(n). |
0 commit comments