606. Construct String from Binary Tree

本文介绍了一种将二叉树转换为字符串的算法,该算法遵循先序遍历的原则,并考虑了空节点的表示方式。文章提供了两种实现思路及对应的Java代码示例。

题目描述:

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.

 class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }

思路一:

class Solution {
    public String tree2str(TreeNode t) {
        if (t == null) return "";
        String result = t.val + "";
        String left = tree2str(t.left);
        String right = tree2str(t.right);
        if (left == "" && right == "") return result;
        if (left == "") return result + "()" + "(" + right + ")";
        if (right == "") return result + "(" + left + ")";
        return result + "(" + left + ")" + "(" + right + ")";
    }
}
class Solution {
    public String tree2str(TreeNode t) {
        if (t == null) return "";
        String left = tree2str(t.left);
        String right = tree2str(t.right);
        if (left == "" && right == "") return t.val + "";
        return t.val + "(" + left + ")" + (right == "" ? "" : "(" + right + ")");
    }
}
思路二:

class Solution {
    public String tree2str(TreeNode t) {
        StringBuilder sb = new StringBuilder();
        return helper(t, sb);
    }
    public String helper(TreeNode t, StringBuilder sb)
    {
        if (t == null) return "";
        sb.append(t.val);
        if (t.left != null || t.right != null)
        {
            sb.append("(");
            helper(t.left, sb);
            sb.append(")");
            if (t.right != null)
            {
                sb.append("(");
                helper(t.right, sb);
                sb.append(")");
            }
        }
        return sb.toString();
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值