algorithm notes: leetcode#606 construct string from binary tree

Problem


Solution


Analysis

Python implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
class :
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
if t is None:
return ''
if t.left is None and t.right is None:
return str(t.val)
if t.right is None:
return str(t.val) + '({})'.format(self.tree2str(t.left))
return str(t.val) + '({})({})'.format(self.tree2str(t.left), self.tree2str(t.right))r

Java implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class {
public String tree2str(TreeNode t) {
if(t == null)
return "";
if(t.left == null && t.right == null)
return Integer.toString(t.val);
if(t.right == null)
return t.val + "(" + tree2str(t.left) + ")";
return t.val + "(" + tree2str(t.left) + ")" + "(" + tree2str(t.right) + ")";
}
}

Time complexity

O(n).

Space complexity

O(n).


606. Construct String from Binary Tree
(中文版) 算法笔记: 力扣#606 根据二叉树创建字符串