为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode655. 输出二叉树 | Print Binary Tree

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10485773.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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

  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:

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

Example 2:

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 的二维字符串数组中输出二叉树,并遵守以下规则:

  1. 行数 m 应当等于给定二叉树的高度。
  2. 列数 n 应当总是奇数。
  3. 根节点的值(以字符串格式给出)应当放在可放置的第一行正中间。根节点所在的行与列会将剩余空间划分为两部分(左下部分和右下部分)。你应该将左子树输出在左下部分,右子树输出在右下部分。左下和右下部分应当有相同的大小。即使一个子树为空而另一个非空,你不需要为空的子树输出任何东西,但仍需要为另一个子树留出足够的空间。然而,如果两个子树都为空则不需要为它们留出任何空间。
  4. 每个未使用的空间应包含一个空的字符串""
  5. 使用相同的规则输出子树。

示例 1:

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

示例 2:

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

示例 3:

输入:
      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 }

 

 

posted @ 2019-03-06 20:30  为敢技术  阅读(254)  评论(0编辑  收藏  举报