Leetcode606. 由二叉树构建字符串

来源:互联网 发布:windows ce 触摸屏 编辑:程序博客网 时间:2024/05/21 10:32

Leetcode606. 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.

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.

Example1:
Input: Binary tree: [1,2,3,4]
1
/ \
2 3
/
4
Output: “1(2(4))(3)”
Explanation: Originally 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)”.

Example2:
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.

解题分析

题目刚拿过来一看可能会有点被吓住了,但其实静下心来思考这个问题,你会发现题目并没有想象中的难。我们先来分析题目给的两个例子,进而分析出由二叉树输出的字符串应满足的要求。

我们先看看第一个例子。根节点1有左右两个子节点2和3,其中子节点2有左子节点4,而输出的字符串为”1(2(4))(3)”。由此不难分析出:当某个节点左右两个子节点均不为空时,应加上(),并在其中加上子节点的值;而当某个节点只存在左子节点时,则可以省略右子节点对应的()。
再来看第二个例子。根节点1有左右两个子节点2和3,其中子节点2有右子节点4,而输出的字符串为”1(2()(4))(3)”。可以看出:当某个节点只存在右子节点时,则不能省略其左子节点对应的()。

分析完输出的字符串的格式要求,再来想下如何遍历二叉树。很显然,采用先序遍历的方法就可以了,在遍历的时候注意判断左右子节点是否为空,就可以顺利解决这个问题。

源代码

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    string tree2str(TreeNode* t) {        if(t == NULL) {            return "";        }        string str = to_string(t->val);        if(t->left != NULL) {            str += '(' + tree2str(t->left) + ')';        }        else if(t->right != NULL) {            str += "()";        }        if(t->right != NULL) {            str += '(' + tree2str(t->right) + ')';        }        return str;    }};

以上只是我对这道题的一些想法,有问题还请在评论区讨论留言~