Skip to content

Commit 2536151

Browse files
solves consruct string from binary tree
1 parent 762c218 commit 2536151

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@
160160
| 599 | [Minimum Index Sum of 2 Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists) | [![Java](assets/java.png)](src/MinimumIndexSumOfTwoLists.java) [![Python](assets/python.png)](python/minimum_index_sum_of_two_lists.py) |
161161
| 604 | 🔒 [Design Compressed String Iterator](https://leetcode.com/problems/design-compressed-string-iterator) | |
162162
| 605 | [Can Place Flowers](https://leetcode.com/problems/can-place-flowers) | [![Java](assets/java.png)](src/CanPlaceFlowers.java) [![Python](assets/python.png)](python/can_place_flowers.py) |
163-
| 606 | [Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree) | |
163+
| 606 | [Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree) | [![Java](assets/java.png)](src/ConstructStringFromBinaryTree.java) [![Python](assets/python.png)](python/construct_string_from_binary_tree.py)|
164164
| 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees) | |
165165
| 624 | [Maximum Distance in Arrays](https://leetcode.com/problems/maximum-distance-in-arrays) | |
166166
| 628 | [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers) | |

Diff for: python/construct_string_from_binary_tree.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Definition for a binary tree node.
2+
class TreeNode:
3+
def __init__(self, val=0, left=None, right=None):
4+
self.val = val
5+
self.left = left
6+
self.right = right
7+
8+
9+
class Solution:
10+
def tree2str(self, root: TreeNode) -> str:
11+
if root is None: return ''
12+
if root.left is None and root.right is None: return f'{root.val}'
13+
if root.right is None: return f'{root.val}({self.tree2str(root.left)})'
14+
return f'{root.val}({self.tree2str(root.left)})({self.tree2str(root.right)})'

Diff for: src/ConstructStringFromBinaryTree.java

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
public class ConstructStringFromBinaryTree {
2+
public String tree2str(TreeNode root) {
3+
if (root == null) return "";
4+
if (root.left == null && root.right == null) return root.val + "";
5+
return root.val + "(" + tree2str(root.left) + ")"
6+
+ (root.right == null ? "" : "(" + tree2str(root.right) + ")");
7+
}
8+
}

0 commit comments

Comments
 (0)