leetcode (Construct String from Binary Tree)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85110085

Title:Construct String from Binary Tree    606

Difficulty:Easy

原题leetcode地址:https://leetcode.com/problems/construct-string-from-binary-tree/

1.    注解见代码注释

时间复杂度:O(n),遍历Tree。

空间复杂度:O(1),没有申请额外空间。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public static String tree2str(TreeNode t) {

        if (t == null) {
            return "";
        }

        if (t.left == null && t.right == null) {
            return t.val + "";
        }

        if (t.right == null) {
            return t.val + "(" + tree2str(t.left) + ")";
        }

        return t.val + "(" + tree2str(t.left) + ")(" + tree2str(t.right) + ")";

    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/85110085