[LeetCode] Construct String from Binary Tree 根据二叉树创建字符串

简介: You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.

Example 1:

Input: Binary tree: [1,2,3,4]
       1
     /   \
    2     3
   /    
  4     
Output: "1(2(4))(3)"
Explanation: Originallay it needs to be "1(2(4)())(3()())",
but you need to omit all the unnecessary empty parenthesis pairs.
And it will be "1(2(4))(3)".

Example 2:

Input: Binary tree: [1,2,3,null,4]
       1
     /   \
    2     3
     \  
      4 
Output: "1(2()(4))(3)"
Explanation: Almost the same as the first example,
except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.

这道题给我们了一个二叉树,让我们创建对应的字符串,之前有一道正好反过来的题Construct Binary Tree from String。对于二叉树的处理,递归肯定是王道啊。想想如何来实现递归函数,我们观察到题目中的例子,发现如果左子结点为空,右子结点不为空时,需要在父结点后加上个空括号,而右子结点如果不存在,或者左右子结点都不存在就不需要这么做。那我们在递归函数中,如果当前结点不存在,直接返回,然后要在当前结点值前面加上左括号,然后判断,如果左子结点不存在,而右子结点存在的话,要在结果res后加上个空括号,然后分别对左右子结点调用递归函数,调用完之后要加上右括号,形成封闭的括号。由于最外面一层的括号不需要,所以我们再返回最终结果之前要去掉首尾的括号,参见代码如下:

解法一:
public:
    string tree2str(TreeNode* t) {
        if (!t) return "";
        string res = "";
        helper(t, res);
        return string(res.begin() + 1, res.end() - 1);
    }
    void helper(TreeNode* t, string& res) {
        if (!t) return;
        res += "(" + to_string(t->val);
        if (!t->left && t->right) res += "()";
        helper(t->left, res);
        helper(t->right, res);
        res += ")";
    }
};

下面来看一种不用额外函数的递归写法,这种做法是一开始调用递归函数求出左右子结点的返回字符串,如果左右结果串均为空,则直接返回当前结点值;如果左子结果串为空,那么返回当前结果res,加上一个空括号,再加上放在括号中的右子结果串;如果右子结果串为空,那么发返回当前结果res,加上放在括号中的左子结果串;如果左右子结果串都存在,那么返回当前结果,加上分别放在括号中的左右子结果串,参见代码如下:

解法二:

public:
    string tree2str(TreeNode* t) {
        if (!t) return "";
        string res = to_string(t->val);
        string left = tree2str(t->left), right = tree2str(t->right);
        if (left == "" && right == "") return res;
        if (left == "") return res + "()" + "(" + right + ")";
        if (right == "") return res + "(" + left + ")";
        return res + "(" + left + ")" + "(" + right + ")";
    }
}; 

下面这种解法更加简洁,由热心网友edyyy提供,思路和上面解法相同,参见代码如下: 

解法三:

public:
    string tree2str(TreeNode* t) {
        if (!t) return "";
        string res = to_string(t->val);
        if (!t->left && !t->right) return res;
        res += "(" + tree2str(t->left) + ")";
        if (t->right) res += "(" + tree2str(t->right) + ")";
        return res;
    }
};

参考资料:

https://discuss.leetcode.com/topic/91308/java-solution-tree-traversal

本文转自博客园Grandyang的博客,原文链接:[LeetCode] Construct String from Binary Tree 根据二叉树创建字符串

,如需转载请自行联系原博主。

相关文章
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
326 100
|
3月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
440 99
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
3月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
4月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
287 92
|
5月前
|
自然语言处理 Java Apache
在Java中将String字符串转换为算术表达式并计算
具体的实现逻辑需要填写在 `Tokenizer`和 `ExpressionParser`类中,这里只提供了大概的框架。在实际实现时 `Tokenizer`应该提供分词逻辑,把输入的字符串转换成Token序列。而 `ExpressionParser`应当通过递归下降的方式依次解析
339 14
|
7月前
|
Go 开发者 索引
【LeetCode 热题100】路径与祖先:二叉树中的深度追踪技巧(力扣33 / 81/ 153/154)(Go语言版)
本文深入探讨了LeetCode中四道关于「搜索旋转排序数组」的经典题目,涵盖了无重复和有重复元素的情况。通过二分查找的变形应用,文章详细解析了每道题的解题思路和Go语言实现代码。关键点包括判断有序区间、处理重复元素以及如何缩小搜索范围。文章还总结了各题的异同,并推荐了类似题目,帮助读者全面掌握二分查找在旋转数组中的应用。无论是初学者还是有经验的开发者,都能从中获得实用的解题技巧和代码实现方法。
311 14
|
8月前
|
Go
【LeetCode 热题100】路径与祖先:二叉树中的深度追踪技巧(力扣437 / 236 )(Go语言版)
本文深入探讨二叉树中路径与祖先问题,涵盖两道经典题目:LeetCode 437(路径总和 III)和236(最近公共祖先)。对于路径总和 III,文章分析了双递归暴力解法与前缀和优化方法,后者通过哈希表记录路径和,将时间复杂度从O(n²)降至O(n)。在最近公共祖先问题中,采用后序遍历递归查找,利用“自底向上”的思路确定最近公共祖先节点。文中详细解析代码实现与核心要点,帮助读者掌握深度追踪技巧,理解树结构中路径与节点关系的本质。这类问题在面试中高频出现,掌握其解法意义重大。
185 4