Leetcode之Construct String from Binary Tree 问题

来源:互联网 发布:什么是中文域名 编辑:程序博客网 时间:2024/05/29 15:08

问题描述:

You need to construct a string consists of parenthesis and integers from a binary tree with thepreorder traversingway.

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.

示例一:

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)".

示例二:

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 String from Binary Tree (详细地址:https://leetcode.com/problems/construct-string-from-binary-tree/description/)

思路分析:在这我们就采用简单的递归的方式吧,如果要是是用栈来先序遍历的话,肯定也是可行的。既然是递归,那么就要选定递归的出口。

1.)如果根节点为空,则应该构造成 val + "";

2.)如果这个结点是根节点了,那直接返回val就行了;

3.)如果这个结点只有左结点,那么返回的应该是val + (left)的形式;

4.)如果这个结点只有右结点,那么返回的应该是val + () + (right)的形式。

记住,最后根节点咱们得汇总一下,因为前面考虑的都是子节点,最后结果为val + (left) + (right)。

代码:










原创粉丝点击