[Leetcode] Binary tree-- 606. 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

Solution: 

 1. use recursive way

  e.g.

     1

  /   \
      2     3

     /  \

    4    5

  2‘s subtree have the similar substructure, having the similar problem.  2(4)(5)

  inside the whole answer 1(2(4)(5))(3)

  so it is easy to use recursive way to construct the string

1         if t is None:
2             return ""
3         strRes = str(t.val)
4
5         if t.left or t.right:
6             strRes += "(" + self.tree2str(t.left) + ")"
7         if  t.right:
8             strRes += "(" + self.tree2str(t.right) + ")"
9         return strRes

  2.  use iterative way

how to add right parentheses ")"?  one way is we can judge to visit the node again to complete the ")". Hence if it is visited before, then we add ")", also pop from the stack

In one word, we use visited node set to record visited or not, and also stack to record traverse nodes as normal DFS

 1         stk = []           #stack
 2         visitedSet = set()
 3         strRes = ""
 4         if t is not None:
 5             #put t into stack
 6             stk.append(t)
 7         while (len(stk)):
 8             node = stk[-1]
 9             #print ("node: ", node.val)
10             if node not in visitedSet:
11                 visitedSet.add(node)
12                 #add "(" + val
13                 strRes += "(" + str(node.val)
14                 if node.right is not None:
15                     stk.append(node.right)
16                 if node.left is not None:
17                     stk.append(node.left)
18                 elif node.right is not None:
19                     strRes += "()"                 #make sure it doesn‘t affect the one-to-one mapping relationship
20
21             else:
22                 strRes += ")"
23                 #pop node
24                 stk.pop()
25         return strRes[1:-1]                   #remove the first and last parenthesis
时间: 2024-11-19 14:07:46

[Leetcode] Binary tree-- 606. Construct String from Binary Tree的相关文章

606. Construct String from Binary Tree 【easy】

606. Construct String from Binary Tree [easy] 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

606. 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 t

606. Construct String from Binary Treedigui (递归)

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 t

[LeetCode] Construct String from Binary Tree

Invert a binary tree. 4 / 2 7 / \ / 1 3 6 9 to 4 / 7 2 / \ / 9 6 3 1 Trivia:This problem was inspired by this original tweet by Max Howell: Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a wh

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 t

[Algorithm] 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 t

【Leetcode长征系列】Construct Binary Tree from Inorder and Postorder Traversal

原题: Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. 思路:和上一题一样,后续我们可以通过最后一个值得到根的值,同样可以通过定位根的值得到左右子树的子集,递归求解即可. 代码: /** * Definition for binary tree * struct Tre

LeetCode OJ - Convert Sorted Array/List to Binary Search Tree

虚函数使用的时机 为什么虚函数不总是适用? 1. 虚函数有事会带来很大的消耗: 2. 虚函数不总是提供所需的行为: 3. 当我们不考虑继承当前类时,不必使用虚函数. 必须使用虚函数的情况: 1. 当你想删除一个表面上指向基类对象,实际却是指向派生类对象的指针,就需要虚析构函数. LeetCode OJ - Convert Sorted Array/List to Binary Search Tree,布布扣,bubuko.com LeetCode OJ - Convert Sorted Arra

leetcode -day17 Path Sum I II & Flatten Binary Tree to Linked List & Minimum Depth of Binary Tree

1.  Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 r