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;
}