1. 程式人生 > >[LeetCode] Construct String from Binary Tree 根據二叉樹建立字串

[LeetCode] Construct String from Binary Tree 根據二叉樹建立字串

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.

Example 1:

Input: Binary tree: [1,2,3,4]
       1
     /   \
    2     3
   /    
  4     

Output: "1(2(4))(3)"

Explanation: Originallay 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)".

Example 2:

Input: Binary tree: [1,2,3,null,4]
       1
     /   \
    2     3
     \  
      4 

Output: "1(2()(4))(3)"

Explanation: Almost the same as the first example,
except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.

這道題給我們了一個二叉樹,讓我們建立對應的字串,之前有一道正好反過來的題Construct Binary Tree from String。對於二叉樹的處理,遞迴肯定是王道啊。想想如何來實現遞迴函式,我們觀察到題目中的例子,發現如果左子結點為空,右子結點不為空時,需要在父結點後加上個空括號,而右子結點如果不存在,或者左右子結點都不存在就不需要這麼做。那我們在遞迴函式中,如果當前結點不存在,直接返回,然後要在當前結點值前面加上左括號,然後判斷,如果左子結點不存在,而右子結點存在的話,要在結果res後加上個空括號,然後分別對左右子結點呼叫遞迴函式,呼叫完之後要加上右括號,形成封閉的括號。由於最外面一層的括號不需要,所以我們再返回最終結果之前要去掉首尾的括號,參見程式碼如下: