Construct String from Binary Tree
给一个数组, 返回有括号表示后的pre order traversing..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
/** * Definition for a binary tree node. * public 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 right = tree2str(t.right); String left = tree2str(t.left); String res = t.val+""; if(right.equals("") && left.equals("")) return res; else if(right.equals("")){ return res + "(" + left + ")"; } else return res + "(" + left + ")" + "(" + right + ")"; } } |