·
·
文章目录
  1. 题目介绍
  2. 复杂度
  3. 解题思路

Construct Binary Tree from Inorder and Postorder Traversal

题目介绍

LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal

复杂度

时间复杂度: O(n), 空间复杂度: O(n)

解题思路

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}

class Solution {
func buildTree(_ inorder: [Int], _ postorder: [Int]) -> TreeNode? {
guard !inorder.isEmpty else {
return nil
}
let root = TreeNode(postorder.last!)
let index = inorder.firstIndex(of: root.val)!
root.left = buildTree(index.distance(to: 0) < 0 ? Array(inorder[0..<index]) : [], index.distance(to: 0) < 0 ? Array(postorder[0..<index]) : [])
root.right = buildTree(index.distance(to: inorder.count-1) > 0 ? Array(inorder[index+1..<inorder.count]) : [], index.distance(to: 0) <= 0 ? Array(postorder[index..<postorder.count-1]) : [])
return root
}
}
**版权声明**

Ivan’s Blog by Ivan Ye is licensed under a Creative Commons BY-NC-ND 4.0 International License.
叶帆创作并维护的叶帆的博客博客采用创作共用保留署名-非商业-禁止演绎4.0国际许可证

本文首发于Ivan’s Blog | 叶帆的博客博客( http://yeziahehe.com ),版权所有,侵权必究。

本文链接:http://yeziahehe.com/2020/05/01/ConstructBinaryTreeFromInorderAndPostorderTraversal/

支持一下
扫一扫,支持yeziahehe
  • 微信扫一扫
  • 支付宝扫一扫