问题描述
解法
分析
Python 实现
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))
|
Java 实现
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) + ")"; } }
|
时间复杂度
O(n).
空间复杂度
O(n).
链接
606. Construct String from Binary Tree
606. 根据二叉树创建字符串
(English version) Algorithm Notes: Leetcode#606 Construct String from Binary Tree
近期评论