0
点赞
收藏
分享

微信扫一扫

Leetcode 606. 根据二叉树创建字符串

Leetcode 606. 根据二叉树创建字符串

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public String str = "";
    public void tree2strChild(TreeNode root) {
        if(root == null) {
            return;
        }
        str += root.val;
        if(root.left == null) {
            if(root.right == null) {
                return;
            }else {
                str +="()";
            }
        }else {
            str +="(";
            tree2strChild(root.left);
            str +=")";
        }

        if(root.right == null) {
            return;
        }else {
            str +="(";
            tree2strChild(root.right);
            str +=")";
        }
    }

    public String tree2str(TreeNode root) {
        if(root == null) {
            return str;
        }
        tree2strChild(root);
        return str;
    }
}
举报

相关推荐

0 条评论