https://leetcode.cn/problems/construct-string-from-binary-tree/description/
1.递归遍历二叉树:采用前序遍历(根→左→右)的顺序处理每个节点,确保节点值的输出顺序符合前序逻辑。 2.节点值与括号规则:


左边为空,右边不为空 此时需要加上小括号()
class Solution {
public String tree2str(TreeNode t) {
StringBuilder sb = new StringBuilder();
//掉用
tree2strChild(t, sb);
return sb.toString();
}
public void tree2strChild(TreeNode t, StringBuilder stringBuilder) {
if (t == null) {
return;
}
stringBuilder.append(t.val);
// 判断当前t的左边
if (t.left != null) {
stringBuilder.append("(");
//加左括号
tree2strChild(t.left, stringBuilder);
//进行左视图的递归
stringBuilder.append(")");
//最左边的完成了,在判断右子树
} else {
//如果左孩子为空,但右孩子不为空,要保留左括号占位
if (t.right != null) {
stringBuilder.append("()");
//右边不为空
}
}
// 判断当前t的右边
if (t.right != null) {
stringBuilder.append("(");
tree2strChild(t.right, stringBuilder);
stringBuilder.append(")");
} else {
return;
// 右孩子也为空时无需操作
}
}
}