606. Construct String from Binary Tree - Medium
前往題目
想法
Preorder
的順序,然後在數字左右加上括號
思路
Preorder
順序- 刻意跳過
leaf
的左右子節點,否則會加無謂的括號 - 建立左子樹
- 建立右子樹,但只有右子樹不為空才建立
Code
第一次寫出來沒考慮到遇到leaf
要直接回傳,否則會加入空的括號
class Solution {
StringBuilder res;
public String tree2str(TreeNode root) {
res = new StringBuilder("");
build(root);
return res.toString();
}
private void build(TreeNode node) {
if (node == null) return;
res.append(node.val);
// return at leaf
if (node.left == null && node.right == null) return;
// Build left
res.append("(");
build(node.left);
res.append(")");
// Build right only if it's not null
if (node.right != null) {
res.append("(");
build(node.right);
res.append(")");
}
}
}
606. Construct String from Binary Tree - Medium
https://f88083.github.io/2024/10/23/606-Construct-String-from-Binary-Tree-Medium/