[Swift]LeetCode655. 輸出二叉樹 | Print Binary Tree

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-gqbdkghx-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Print a binary tree in an m*n 2D string array following these rules:node

  1. The row number m should be equal to the height of the given binary tree.
  2. The column number n should always be an odd number.
  3. The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don't need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don't need to leave space for both of them.
  4. Each unused space should contain an empty string "".
  5. Print the subtrees following the same rules.

Example 1:git

Input:
     1
    /
   2
Output:
[["", "1", ""],
 ["2", "", ""]]

Example 2:github

Input:
     1
    / \
   2   3
    \
     4
Output:
[["", "", "", "1", "", "", ""],
 ["", "2", "", "", "", "3", ""],
 ["", "", "4", "", "", "", ""]]

Example 3:數組

Input:
      1
     / \
    2   5
   / 
  3 
 / 
4 
Output:

[["",  "",  "", "",  "", "", "", "1", "",  "",  "",  "",  "", "", ""]
 ["",  "",  "", "2", "", "", "", "",  "",  "",  "",  "5", "", "", ""]
 ["",  "3", "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]
 ["4", "",  "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]]

Note: The height of binary tree is in the range of [1, 10].微信


在一個 m*n 的二維字符串數組中輸出二叉樹,並遵照如下規則:app

  1. 行數 m 應當等於給定二叉樹的高度。
  2. 列數 n 應當老是奇數。
  3. 根節點的值(以字符串格式給出)應當放在可放置的第一行正中間。根節點所在的行與列會將剩餘空間劃分爲兩部分(左下部分和右下部分)。你應該將左子樹輸出在左下部分,右子樹輸出在右下部分。左下和右下部分應當有相同的大小。即便一個子樹爲空而另外一個非空,你不須要爲空的子樹輸出任何東西,但仍須要爲另外一個子樹留出足夠的空間。然而,若是兩個子樹都爲空則不須要爲它們留出任何空間。
  4. 每一個未使用的空間應包含一個空的字符串""
  5. 使用相同的規則輸出子樹。

示例 1:spa

輸入:
     1
    /
   2
輸出:
[["", "1", ""],
 ["2", "", ""]]

示例 2:rest

輸入:
     1
    / \
   2   3
    \
     4
輸出:
[["", "", "", "1", "", "", ""],
 ["", "2", "", "", "", "3", ""],
 ["", "", "4", "", "", "", ""]]

示例 3:code

輸入:
      1
     / \
    2   5
   / 
  3 
 / 
4 
輸出:
[["",  "",  "", "",  "", "", "", "1", "",  "",  "",  "",  "", "", ""]
 ["",  "",  "", "2", "", "", "", "",  "",  "",  "",  "5", "", "", ""]
 ["",  "3", "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]
 ["4", "",  "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]]

注意: 二叉樹的高度在範圍 [1, 10] 中。


16ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func printTree(_ root: TreeNode?) -> [[String]] {
16         let h = getHeight(root)
17         let w = 2 << (h - 1) - 1
18         var res = [[String]]()
19         for _ in 0 ..< h {
20             let row = [String].init(repeating: "", count: w)
21             res.append(row)
22         }
23         fill(root, &res, 0, 0, w - 1)
24         return res
25     }
26     
27     private func getHeight(_ root: TreeNode?) -> Int {
28         guard let node = root else {
29             return 0
30         }
31         return max(getHeight(node.left), getHeight(node.right)) + 1
32     }
33     
34     private func fill(_ root: TreeNode?, _ grid: inout [[String]], _ h: Int, _ l: Int, _ r: Int) {
35         guard let node = root else {
36             return
37         }
38         let mid = (l + r) / 2
39         grid[h][mid] = String(node.val)
40         fill(node.left, &grid, h + 1, l, mid - 1)
41         fill(node.right, &grid, h + 1, mid + 1, r)
42     }
43 }

Runtime: 20 ms
Memory Usage: 19.2 MB
 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func printTree(_ root: TreeNode?) -> [[String]] {
16         var h:Int = getHeight(root)       
17         var w:Int = Int(pow(2,Double(h)) - 1)
18         var res:[[String]] = [[String]](repeating:[String](repeating:String(),count:w),count:h)
19         helper(root, 0, w - 1, 0, h, &res)
20         return res
21     }
22     
23     func getHeight(_ node: TreeNode?) -> Int
24     {
25         if node == nil {return 0}
26         return 1 + max(getHeight(node?.left), getHeight(node?.right))
27     }
28     
29     func helper(_ node: TreeNode?,_ i:Int,_ j:Int,_ curH:Int,_ height:Int,_ res:inout [[String]])
30     {
31         if node == nil || curH == height {return}
32         res[curH][(i + j) / 2] = String(node!.val)
33         helper(node!.left, i, (i + j) / 2, curH + 1, height, &res)
34         helper(node!.right, (i + j) / 2 + 1, j, curH + 1, height, &res)
35     }
36 }

20ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func printTree(_ root: TreeNode?) -> [[String]] {
16         let depth = depthTree(root)
17         return helper(depth, root)
18     }
19     
20     private func helper(_ depth: Int, _ root: TreeNode?) -> [[String]] {
21         if depth <= 0 { return [] }
22         let width = Int(pow(2, Double(depth))) - 1
23         var str = [String](repeating: "", count: width)     
24         if let root = root {
25             let middle = width/2
26             str[middle] = "\(root.val)"
27         }
28         if depth == 1 { return [str] }
29         var res = [[String]]()
30         res.append(str)
31         let resLeft = helper(depth - 1, root?.left)
32         let resRight = helper(depth - 1, root?.right)
33         for i in 0..<resLeft.count {
34             res.append(resLeft[i] + [""] + resRight[i])
35         }
36         return res
37     }
38     
39     private func depthTree(_ root: TreeNode?) -> Int {
40         guard let root = root else { return 0 }
41         return 1 + max(depthTree(root.left), depthTree(root.right))
42     }
43 }
相關文章
相關標籤/搜索