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后加上個空括號,然后分別對左右子結點調用遞歸函數,調用完之后要加上右括號,形成封閉的括號。由於最外面一層的括號不需要,所以我們再返回最終結果之前要去掉首尾的括號,參見代碼如下:
class Solution { public: string tree2str(TreeNode* t) { if (!t) return ""; string res = ""; helper(t, res); return string(res.begin() + 1, res.end() - 1); } void helper(TreeNode* t, string& res) { if (!t) return; res += "(" + to_string(t->val); if (!t->left && t->right) res += "()"; helper(t->left, res); helper(t->right, res); res += ")"; } };
下面來看一種不用額外函數的遞歸寫法,這種做法是一開始調用遞歸函數求出左右子結點的返回字符串,如果左右結果串均為空,則直接返回當前結點值;如果左子結果串為空,那么返回當前結果res,加上一個空括號,再加上放在括號中的右子結果串;如果右子結果串為空,那么發返回當前結果res,加上放在括號中的左子結果串;如果左右子結果串都存在,那么返回當前結果,加上分別放在括號中的左右子結果串,參見代碼如下:
解法二:
class Solution { public: string tree2str(TreeNode* t) { if (!t) return ""; string res = to_string(t->val); string left = tree2str(t->left), right = tree2str(t->right); if (left == "" && right == "") return res; if (left == "") return res + "()" + "(" + right + ")"; if (right == "") return res + "(" + left + ")"; return res + "(" + left + ")" + "(" + right + ")"; } };
下面這種解法更加簡潔,由熱心網友edyyy提供,思路和上面解法相同,參見代碼如下:
解法三:
class Solution { public: string tree2str(TreeNode* t) { if (!t) return ""; string res = to_string(t->val); if (!t->left && !t->right) return res; res += "(" + tree2str(t->left) + ")"; if (t->right) res += "(" + tree2str(t->right) + ")"; return res; } };
類似題目:
Construct Binary Tree from String
參考資料:
https://discuss.leetcode.com/topic/91308/java-solution-tree-traversal