leetcode[Construct String from Binary Tree]//待整理多种解法

来源:互联网 发布:萌拍相机软件 编辑:程序博客网 时间:2024/06/08 13:22

解法一:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {//根据题意,若结点的左子结点为空,则()不能省略private void recurse(TreeNode root, StringBuilder s){if(root == null) return;s.append("" + root.val);//没有孩子结点时直接返回if(root.left == null && root.right == null){return;}//左子树if(root.left == null){s.append("()");} else{s.append("(");recurse(root.left, s);s.append(")");}//右子树if(root.right == null){//什么也不做} else{s.append("(");recurse(root.right, s);s.append(")");}}    public String tree2str(TreeNode t) {        StringBuilder res = new StringBuilder();        recurse(t, res);        return res.toString();    }}


阅读全文
1 0