你需要采用前序遍歷的方式,將一個二叉樹轉換成一個由括號和整數組成的字符串。
空節點則用一對空括號 "()" 表示。而且你需要省略所有不影響字符串與原始二叉樹之間的一對一映射關系的空括號對。
示例 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)"
解釋: 和第一個示例相似,
除了我們不能省略第一個對括號來中斷輸入和輸出之間的一對一映射關系。來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/construct-string-from-binary-tree
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
解法:
?
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
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;}
};
?