leetcode 606. 根據二叉樹建立字串(python)
阿新 • • 發佈:2019-01-27
你需要採用前序遍歷的方式,將一個二叉樹轉換成一個由括號和整陣列成的字串。
空節點則用一對空括號 "()" 表示。而且你需要省略所有不影響字串與原始二叉樹之間的一對一對映關係的空括號對。
示例 1:
輸入: 二叉樹: [1,2,3,4]
1
/ \
2 3
/
4
輸出: "1(2(4))(3)"
解釋: 原本將是“1(2(4)())(3())”,
在你省略所有不必要的空括號對之後,
它將是“1(2(4))(3)”。
示例 2:
輸入: 二叉樹: [1,2,3,null,4] 1 / \ 2 3 \ 4 輸出: "1(2()(4))(3)" 解釋: 和第一個示例相似, 除了我們不能省略第一個對括號來中斷輸入和輸出之間的一對一對映關係。
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def tree2str(self, t): """ :type t: TreeNode :rtype: str """ if not t: return "" res = "" left = self.tree2str(t.left) right = self.tree2str(t.right) if left or right: res += "(%s)" % left if right: res += "(%s)" % right return str(t.val) + res