• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[Swift]LeetCode654.最大二叉树|MaximumBinaryTree

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

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

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

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

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number. 

Construct the maximum tree by the given array and output the root node of this tree.

Example 1:

Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:

      6
    /   \
   3     5
    \    / 
     2  0   
       \
        1 

Note:

  1. The size of the given array will be in the range [1,1000].

给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:

  1. 二叉树的根是数组中的最大元素。
  2. 左子树是通过数组中最大值左边部分构造出的最大二叉树。
  3. 右子树是通过数组中最大值右边部分构造出的最大二叉树。

通过给定的数组构建最大二叉树,并且输出这个树的根节点。

Example 1:

输入: [3,2,1,6,0,5]
输入: 返回下面这棵树的根节点:

      6
    /   \
   3     5
    \    / 
     2  0   
       \
        1

注意:

  1. 给定的数组的大小在 [1, 1000] 之间。

104ms

 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 constructMaximumBinaryTree(_ nums: [Int]) -> TreeNode? {
16         let end = nums.count
17         if (end == 0) {
18             return nil
19         }
20         var nums = nums
21         return construct(&nums, 0, end-1)
22     }
23     
24     func construct(_ nums: inout [Int], _ start: Int, _ end: Int) -> TreeNode {
25         var maxNumber = Int.min; var maxIndex = 0
26 
27         for i in start...end {
28             if (nums[i] >= maxNumber) {
29                 maxNumber = nums[i]
30                 maxIndex = i
31             }
32         }
33         let head = TreeNode(maxNumber)
34         
35         if (start != end) {
36             switch maxIndex {
37                 case start:
38                 head.right = construct(&nums, start+1, end)
39                 case end:
40                 head.left = construct(&nums, start, end-1)
41                 default:
42                 head.left = construct(&nums, start, maxIndex-1)
43                 head.right = construct(&nums, maxIndex+1, end)
44             }
45         }
46         
47         return head
48     }
49 }

108ms

 1 class Solution {
 2     func constructMaximumBinaryTree(_ nums: [Int]) -> TreeNode? {        
 3         
 4         return construct(nums, 0, nums.count)
 5     }
 6     
 7     func construct(_ n: [Int], _ s: Int, _ e: Int) -> TreeNode? {
 8         if s == e { return nil }
 9         
10         let idx = max(n, s, e)
11         
12         var r = TreeNode(n[idx])
13         r.left = construct(n, s, idx)
14         r.right = construct(n, idx+1, e)
15         return r
16     }
17     
18     func max(_ nums: [Int], _ s: Int, _ e: Int) -> Int {
19         var idx = s
20         for i in s..<e {
21                 if nums[idx] < nums[i] { 
22                     idx = i 
23                 }
24             }
25         return idx
26     }
27 }

116ms

 1 class Solution {
 2     func constructMaximumBinaryTree(_ nums: [Int]) -> TreeNode? {
 3         return findMidMax(nums, 0, nums.count - 1)
 4     }
 5     
 6     func findMidMax(_ nums:[Int], _ i:Int, _ j:Int) -> TreeNode? {
 7         
 8         if i < 0 || i >= nums.count {
 9             return nil
10         } else if j < 0 || j >= nums.count {
11             return nil
12         } else if i > j {
13             return nil
14         }
15         
16         
17         
18         var maxNum = Int.min
19         var maxIndex = -1
20         var index = i
21         while (index <= j) {
22             if maxNum < nums[index]{
23                 maxNum = nums[index]
24                 maxIndex = index
25             }
26             index = index + 1
27         }
28         
29         var rootNode = TreeNode(nums[maxIndex])
30         rootNode.left = findMidMax(nums, i, maxIndex - 1)
31         rootNode.right = findMidMax(nums, maxIndex + 1, j)
32         
33         return rootNode
34     }
35 }

120ms

 1 class Solution {
 2     
 3     func constructMaximumBinaryTree(_ nums: [Int]) -> TreeNode? {
 4         var stack = [TreeNode]()
 5         
 6         for i in 0..<nums.count {
 7             var cur = TreeNode(nums[i])
 8             while let last = stack.last, last.val < nums[i] {
 9                 cur.left = last
10                 stack.popLast()
11             }
12             if (!stack.isEmpty) {
13                 stack.last?.right = cur
14             }
15             stack.append(cur)
16         }
17         return stack.first
18     }
19 }

132ms

 1 class Solution {
 2     func constructMaximumBinaryTree(_ nums: [Int]) -> TreeNode? {
 3         if nums.count == 0 { return nil }
 4         if nums.count == 1 { return TreeNode(nums[0]) }
 5         let maxIdx = getMaxIndex(nums)
 6         let tree = TreeNode(nums[maxIdx])
 7         tree.left = constructMaximumBinaryTree(Array(nums.prefix(maxIdx)))
 8         if nums.count > maxIdx {
 9             tree.right = constructMaximumBinaryTree(Array(nums.suffix(from: maxIdx+1)))
10         }
11         
12         return tree
13     }
14     
15     func getMaxIndex(_ arr: [Int]) -> Int {
16         var maxIdx = 0
17         for i in 0..<arr.count {
18             if arr[maxIdx] < arr[i] { maxIdx = i }
19         }
20         return maxIdx
21     }
22 }

Runtime: 156 ms
Memory Usage: 19.9 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 constructMaximumBinaryTree(_ nums: [Int]) -> TreeNode? {
16         var v:[TreeNode?] = [TreeNode?]()
17         for num in nums
18         {
19             var cur:TreeNode? = TreeNode(num)
20             while(!v.isEmpty && v.last!!.val < num)
21             {
22                 cur?.left = v.removeLast()                
23             }
24             if !v.isEmpty
25             {
26                 v.last!!.right = cur
27             }
28             v.append(cur)
29         }
30         return v.first!
31     }
32 }

160ms

 1 class Solution {
 2     func constructMaximumBinaryTree(_ nums: [Int]) -> TreeNode? {
 3         guard !nums.isEmpty else {
 4             return nil
 5         }
 6         var root = -1
 7         var rootIndex = 0
 8         var leftIndex = 0
 9         let rightIndex = nums.count - 1
10         while leftIndex <= rightIndex {
11             let left = nums[leftIndex]
12             if left > root {
13                 root = left
14                 rootIndex = leftIndex
15             }
16             leftIndex += 1
17         }
18         let tree = TreeNode(root)
19         tree.left = constructMaximumBinaryTree(Array(nums[0..<rootIndex]))
20         tree.right = constructMaximumBinaryTree(Array(nums[(rootIndex + 1)...]))
21         return tree
22    }
23 }

 

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
swift 元组发布时间:2022-07-13
下一篇:
Swift 之父 Chris Lattner 访谈录(超长完整版)发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap