题目网址:https://leetcode-cn.com/problems/construct-string-from-binary-tree/
你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private StringBuffer stringBuffer = new StringBuffer();
public String tree2str(TreeNode t) {
//括号省略的规则
if(t == null){
return "";
}
tree2strHelp(t);
stringBuffer.deleteCharAt(0);
stringBuffer.deleteCharAt(stringBuffer.length()-1);
return stringBuffer.toString();
}
private void tree2strHelp(TreeNode root){
if(root == null){
return;
}
//先序
stringBuffer.append("(");
stringBuffer.append(root.val);
tree2strHelp(root.left);
if(root.left == null && root.right != null){
stringBuffer.append("()");
}
tree2strHelp(root.right);
stringBuffer.append(")");
}
}
用先序遍历的方法来解决
注意的是,如果左子树为空,右子树不为空,需要额外领出来占位置

本文介绍如何通过前序遍历将二叉树转换为括号和整数构成的字符串。针对特殊情况,如左子树为空而右子树不空的情况,需额外处理。
1673

被折叠的 条评论
为什么被折叠?



