/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public 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 + ")";
    }
}

https://leetcode.com/problems/construct-string-from-binary-tree/#/description

posted on 2017-06-05 08:23  Sempron2800+  阅读(227)  评论(0编辑  收藏  举报