LeetCode 606. Construct String from Binary Tree

原题链接在这里:https://leetcode.com/problems/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.

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.

题解:

类似Binary Tree Preorder Traversal.

Method 1时recursion方法. 但要注意几种特殊情况:

在left child, right child 都是null的情况下是不iterate child 的

 

如果left child 和right child 中至少有一个不是null 就iterate child 此时无论left child 是否为null 都需要 iterate

 

 

在右侧child 不为null时才iterate.

Time Complexity: O(n). 每个节点走了一遍. Space: O(logn), stack space.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public String tree2str(TreeNode t) {
12         StringBuilder sb = new StringBuilder();
13         preorderTraversal(t, sb);
14         return sb.toString();
15     }
16     
17     private void preorderTraversal(TreeNode t, StringBuilder sb){
18         if(t == null){
19             return;
20         }
21         
22         sb.append(t.val);
23         if(t.left == null && t.right == null){
24             return;
25         }
26         
27         // 到此说明左右child至少有一个不是null 那么就要iterate left child
28         sb.append("(");
29         preorderTraversal(t.left, sb);
30         sb.append(")");
31         
32         // right child在不是null时才会iterate
33         if(t.right != null){
34             sb.append("(");
35             preorderTraversal(t.right, sb);
36             sb.append(")");
37         }
38     }
39 }

AC C++:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     string tree2str(TreeNode* root) {
15         string res;
16         preorder(root, res);
17         return res;
18     }
19     
20     void preorder(TreeNode* root, string& res){
21         if(!root){
22             return;
23         }
24         
25         res += to_string(root->val);
26         if(!root->left && !root->right){
27             return;
28         }
29         
30         res += "(";
31         preorder(root->left, res);
32         res += ")";
33         
34         if(root->right){
35             res += "(";
36             preorder(root->right, res);
37             res += ")";
38         }
39     }
40 };

Method 2是iteration方法. 类似Binary Tree Preorder Traversal的method 2.

多了visited 来标记已经iterate的点. 在peek stack后如果iterate过了就pop stack 并把")"加到结果中.

Time Complexity: O(n). n是节点个数. Space: O(n).

AC Java: 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public String tree2str(TreeNode t) {
12         StringBuilder sb = new StringBuilder();
13         if(t == null){
14             return sb.toString();
15         }
16         
17         Stack<TreeNode> stk = new Stack<TreeNode>();
18         stk.push(t);
19         HashSet<TreeNode> visited = new HashSet<TreeNode>();
20         while(!stk.isEmpty()){
21             TreeNode tn = stk.peek();
22             if(visited.contains(tn)){
23                 stk.pop();
24                 sb.append(")");
25             }else{
26                 visited.add(tn);
27                 sb.append("(" + tn.val);
28                 if(tn.left==null && tn.right!=null){
29                     sb.append("()");
30                 }
31                 if(tn.right != null){
32                     stk.push(tn.right);
33                 }
34                 if(tn.left != null){
35                     stk.push(tn.left);
36                 }
37             }
38         }
39         return sb.toString().substring(1,sb.length()-1);
40     }
41 }

跟上Construct Binary Tree from String.

posted @ 2017-06-25 11:27  Dylan_Java_NYC  阅读(377)  评论(0编辑  收藏  举报