[Swift]LeetCode105. 从前序与中序遍历序列构造二叉树 | Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

    3
   /   9  20
    /     15   7


根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:

    3
   /   9  20
    /     15   7

32ms
 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
15 extension Array {
16     subscript(safe index: Int) -> Element? {
17         guard index >= 0 && index < self.count else {
18             return nil
19         }
20
21         return self[index]
22     }
23 }
24
25 class Solution {
26     func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
27         guard let rootValue = preorder[safe: 0] else {
28             return nil
29         }
30
31         var inorderMap: [Int: Int] = [:]
32         for index in 0..<inorder.count {
33             inorderMap[inorder[index]] = index
34         }
35         let root = TreeNode(rootValue)
36
37         buildNextNode(inorder: inorder, preorder: preorder, inorderMap: inorderMap, currentPreOrderIndex: 0, root: root, tooFarValue: nil)
38
39         return root
40     }
41
42     func buildNextNode(inorder: [Int], preorder: [Int], inorderMap: [Int: Int], currentPreOrderIndex: Int, root: TreeNode, tooFarValue: Int?) -> Int {
43         var currentPreOrderIndex = currentPreOrderIndex
44         guard let nextPreOrderValue = preorder[safe: currentPreOrderIndex + 1] else {
45             return currentPreOrderIndex
46         }
47
48         let childDirection = whichChildDirection(inorder: inorder, inorderMap: inorderMap, knownValue: root.val, potentialChildValue: nextPreOrderValue, tooFarValue: tooFarValue)
49
50         guard let direction = childDirection else {
51             // not a child
52             return currentPreOrderIndex
53         }
54
55         let childNode = TreeNode(nextPreOrderValue)
56
57         if direction {
58             // right child
59             root.right = childNode
60             return buildNextNode(inorder: inorder, preorder: preorder, inorderMap: inorderMap, currentPreOrderIndex: currentPreOrderIndex + 1, root: childNode, tooFarValue: tooFarValue)
61
62         } else {
63             // left child
64             root.left = childNode
65             currentPreOrderIndex = buildNextNode(inorder: inorder, preorder: preorder, inorderMap: inorderMap, currentPreOrderIndex: currentPreOrderIndex + 1, root: childNode, tooFarValue: root.val)
66             return buildNextNode(inorder: inorder, preorder: preorder, inorderMap: inorderMap, currentPreOrderIndex: currentPreOrderIndex, root: root, tooFarValue: tooFarValue)
67         }
68
69         return currentPreOrderIndex
70     }
71
72     /**
73      false: left child
74      true: right child
75      nil: neither child
76      */
77     func whichChildDirection(inorder: [Int], inorderMap: [Int: Int], knownValue: Int, potentialChildValue: Int, tooFarValue: Int?) -> Bool? {
78         let potentialChildIndex = inorderMap[potentialChildValue]! // guarenteed to be in the map
79         let knownIndex = inorderMap[knownValue]! // guarenteed to be in the map
80
81         if potentialChildIndex < knownIndex {
82             return false
83         }
84
85         if let tooFarValue = tooFarValue, let tooFarIndex = inorderMap[tooFarValue] {
86             if tooFarIndex < potentialChildIndex {
87                 return nil
88             }
89         }
90
91         return true
92     }
93 }


36ms

 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 buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
16
17         guard preorder.count > 0, inorder.count > 0 else {
18             return nil
19         }
20
21         var inorderDict = [Int: Int]()
22         for (i, item) in inorder.enumerated() {
23             inorderDict[item] = i
24         }
25
26         return create(inorderDict, preorder, 0, preorder.count - 1, inorder, 0 , inorder.count - 1)
27
28     }
29
30     func create(_ inorderDict: [Int: Int], _ preorder: [Int], _ preLow: Int, _ preHi: Int, _ inorder: [Int], _ inLow: Int, _ inHi: Int) -> TreeNode? {
31
32         if preLow > preHi {  //debug
33             return nil
34         }
35
36         var root = TreeNode(preorder[preLow])
37         let rootIndex = inorderDict[preorder[preLow]]! // debug: dict value is optional, must be unwrapped
38         let leftNum = rootIndex - inLow // debug
39
40         root.left = create(inorderDict, preorder, preLow + 1, preLow + leftNum, inorder, inLow, rootIndex - 1)
41         root.right = create(inorderDict, preorder, preLow + leftNum + 1, preHi, inorder, rootIndex + 1, inHi)
42
43         return root
44     }
45 }


44ms

 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 buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
16         if preorder.count == 0 {
17             return nil
18         }
19
20         var map = [Int: Int]()
21         for i in 0..<inorder.count {
22             map[inorder[i]] = i
23         }
24
25         var stack = [TreeNode]()
26         var value = preorder[0]
27         let root = TreeNode(value)
28
29         stack.append(root)
30         for i in 1..<preorder.count {
31             value = preorder[i]
32             let node = TreeNode(value)
33             if map[value]! < map[stack.last!.val]! {
34                 stack.last!.left = node
35             } else {
36                 var parent: TreeNode? = nil
37                 while !stack.isEmpty && map[value]! > map[stack.last!.val]! {
38                     parent = stack.removeLast()
39                 }
40                 parent?.right = node
41             }
42             stack.append(node)
43         }
44
45         return root
46     }
47 }


56ms

 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 buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
16
17         guard !preorder.isEmpty && !inorder.isEmpty else {
18             return nil
19         }
20
21         return buildTree(preorder, 0, preorder.count-1, inorder, 0, inorder.count-1)
22     }
23
24     func buildTree(_ preorder: [Int], _ preStart: Int, _ preEnd: Int, _ inorder: [Int], _ inStart: Int, _ inEnd: Int) -> TreeNode? {
25
26         guard preStart <= preEnd && inStart <= inEnd else {
27             return nil
28         }
29
30         var rootVal = preorder[preStart]
31         var root = TreeNode(rootVal)
32         var mid: Int = 0
33
34         for i in inStart...inEnd {
35             if inorder[i] == rootVal {
36                 mid = i
37                 break
38             }
39         }
40
41         root.left = buildTree(preorder, preStart+1, preStart + mid - inStart, inorder, inStart, mid - 1)
42         root.right = buildTree(preorder, preStart + mid - inStart + 1, preEnd, inorder, mid+1, inEnd)
43         return root
44     }
45 }


160ms

 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 buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
16         let len = preorder.count
17         if len == 0 { return nil }
18         let root = TreeNode(preorder[0])
19
20         var i = 0
21         while i < len {
22             if inorder[i] == root.val {
23                 break
24             }
25             i += 1
26         }
27
28         if i > 0 {
29             root.left = buildTree(Array(preorder[1...i]), Array(inorder[..<i]))
30         }
31         if i < len-1 {
32             root.right = buildTree(Array(preorder[(i+1)...]), Array(inorder[(i+1)...]))
33         }
34
35         return root
36     }
37 }


240ms

 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     // 根据中序和前序遍历构建二叉树
16     func buildTree(_ inorder: [Int], _ preorder: [Int]) -> TreeNode? {
17
18         if inorder.count <= 0 || preorder.count <= 0{
19             return nil
20         }
21         /*
22          *  后序遍历的最后一个节点肯定是整个树的根节点
23          */
24         return buildTrees(preorder, inorder)
25     }
26
27     func buildTrees(_ inorder: [Int], _ preorder: [Int]) -> TreeNode{
28
29         // 根据前序遍历的第一个节点作为根节点
30         let root = TreeNode.init(preorder[0])
31
32         // 根据中序遍历计算根节点左右子节点的个数
33         var indexRoot: Int = -1
34
35         for index in 0..<inorder.count{
36             if inorder[index] == preorder[0]{
37                 indexRoot = index
38                 break
39             }
40         }
41
42         // 左子节点的个数
43         let leftNum = indexRoot
44         // 右子节点的个数
45         let rightNum = inorder.count - indexRoot - 1
46
47         // 生成新的左右子树
48         if indexRoot > 0{
49             let leftNode = buildTrees([Int](inorder[0...indexRoot - 1]), [Int](preorder[1...leftNum]))
50             root.left = leftNode
51         }
52         if indexRoot < inorder.count - 1{
53             let rightNode = buildTrees([Int](inorder[indexRoot + 1...inorder.count - 1]), [Int](preorder[leftNum + 1...leftNum + rightNum]))
54             root.right = rightNode
55         }
56         return root
57     }
58 }


288ms

 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 buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
16
17         if preorder.count == 0 {
18             return nil
19         }
20
21         if preorder.count == 1 {
22             let val = preorder[0]
23             let root = TreeNode(val)
24             return root
25         }
26
27         let val = preorder[0]
28         let root = TreeNode(val)
29
30         var rootIndex = 0
31         for i in 0..<inorder.count {
32             if inorder[i] == val {
33                 rootIndex = i
34             }
35         }
36
37         var tmpPreorder = [Int]()
38         if rootIndex > 0 {
39             for i in 1...rootIndex {
40                 tmpPreorder.append(preorder[i])
41             }
42         }
43
44         var tmpInorder = [Int]()
45         for i in 0..<rootIndex {
46             tmpInorder.append(inorder[i])
47         }
48
49         root.left = buildTree(tmpPreorder, tmpInorder)
50
51         tmpPreorder = [Int]()
52         for i in rootIndex+1..<preorder.count {
53             tmpPreorder.append(preorder[i])
54         }
55
56         tmpInorder = [Int]()
57         for i in rootIndex+1..<inorder.count {
58             tmpInorder.append(inorder[i])
59         }
60
61         root.right = buildTree(tmpPreorder, tmpInorder)
62
63         return root
64     }
65 }


328ms

 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 buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
16         guard preorder.count != 0, inorder.count != 0, preorder.count == inorder.count else { return nil }
17         let root = TreeNode(preorder[0])
18         let rootInOrderIndex = inorder.index(of: root.val) ?? -1
19         let leftInOrder = Array(inorder[0..<rootInOrderIndex])
20         let leftPreOrderStartIndex = 1
21         let leftPreOrderEndIndexExclusive = leftPreOrderStartIndex + leftInOrder.count
22         let leftPreOrder = Array(preorder[leftPreOrderStartIndex..<leftPreOrderEndIndexExclusive])
23         root.left = buildTree(leftPreOrder, leftInOrder)
24
25         let rightInOrder = Array(inorder[rootInOrderIndex+1..<inorder.count])
26         let rightPreOrder = Array(preorder[leftPreOrderEndIndexExclusive..<preorder.count])
27         root.right = buildTree(rightPreOrder, rightInOrder)
28         return root
29     }
30 }


332ms

 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 buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
16         var inorder = inorder
17         var preorder = preorder
18         var root: TreeNode
19         if preorder.count < 1{
20             return nil
21         }
22         let first = preorder.removeFirst()
23         root = TreeNode(first)
24         let index = inorder.index(of: first)!
25         let lin = Array(inorder[0..<index])
26         let lpro = Array(preorder[0..<index])
27         root.left = buildTree(lpro, lin)
28         let rin = Array(inorder[(index+1)...])
29         let rpro = Array(preorder[index...])
30         root.right = buildTree(rpro, rin)
31         return root
32     }
33 }

原文地址:https://www.cnblogs.com/strengthen/p/9950714.html

时间: 2024-10-27 05:24:33

[Swift]LeetCode105. 从前序与中序遍历序列构造二叉树 | Construct Binary Tree from Preorder and Inorder Traversal的相关文章

LeetCode105. 从前序与中序遍历序列构造二叉树

105. 从前序与中序遍历序列构造二叉树 描述 根据一棵树的前序遍历与中序遍历构造二叉树. 注意: 你可以假设树中没有重复的元素. 示例 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7] 返回如下的二叉树: 3 / 9 20 / 15 7 思路 一颗二叉树,对于前序遍历来说,其第一个元素一定是这棵树的根节点.在中序遍历中找到这个元素所在的位置,那么它的左半部分就是其左子树,右半部分就是其右子树. 重复上述过程, 通过

【2】【leetcode-105,106】 从前序与中序遍历序列构造二叉树,从中序与后序遍历序列构造二叉树

105. 从前序与中序遍历序列构造二叉树 (没思路,典型记住思路好做) 根据一棵树的前序遍历与中序遍历构造二叉树. 注意:你可以假设树中没有重复的元素. 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7] 返回如下的二叉树: 3 / 9 20 / 15 7 链接:https://www.nowcoder.com/questionTerminal/0ee054a8767c4a6c96ddab65e08688f4来源:牛客

[98]验证二叉搜索树&amp;[105]从前序与中序遍历序列构造二叉树

扯闲话时间...很长一段时间没有刷题了,因为工作做得一团糟,惨遭领导怒批,心理压力大得一批导致工作时间特别长又没产出,所以刷题就搁置了... (小声BB)其实感觉领导有点刀子嘴豆腐心,一面说着"公司没义务从零培养新人,我自己也很久不带新人了",一面又给我讲了好多基础知识... 好了,言归正传,今天分享两道题,同类型的,力扣(leetcode中国)给的标签都是深度优先搜索,但是我都没想出来怎么用深度优先,所以都采用了递归. 这里提一句,曾经有位前辈和我说实际工作中递归并不常用,因为递归长

【leetcode 105. 从前序与中序遍历序列构造二叉树】解题报告

前往 中序,后序遍历构造二叉树, 中序,前序遍历构造二叉树 TreeNode* build(vector<int>& preorder, int l1, int r1, vector<int>& inorder, int l2, int r2) { if (l1>r1) return nullptr; int x=preorder[l1], i=0; // 确定当前根节点 for(i=l2;inorder[i]!=x&&i<r2;++i)

105 Construct Binary Tree from Preorder and Inorder Traversal 从前序与中序遍历序列构造二叉树

给定一棵树的前序遍历与中序遍历,依据此构造二叉树.注意:你可以假设树中没有重复的元素.例如,给出前序遍历 = [3,9,20,15,7]中序遍历 = [9,3,15,20,7]返回如下的二叉树:    3   / \  9  20    /  \   15   7详见:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/ /** * Definiti

leetcode 105. 从前序与中序遍历序列构造二叉树

根据一棵树的前序遍历与中序遍历构造二叉树. 注意:你可以假设树中没有重复的元素. 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7] 返回如下的二叉树: 3 / 9 20 / 15 7 1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *righ

105. 从前序与中序遍历序列构造二叉树

题目描述 根据一棵树的前序遍历与中序遍历构造二叉树. 注意: 你可以假设树中没有重复的元素. 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7] 返回如下的二叉树: 3 / 9 20 / 15 7 分析 这题剑指offer中出现过,虽然通过了,但是提交到leetcode上就特别差: 56 ms 75.9 MB 又看了别人的思路: (递归) O(n) 递归建立整棵二叉树:先递归创建左右子树,然后创建根节点,并让指针指向两

LeetCode--105--从前序与中序遍历序列构造二叉树(python)

根据一棵树的前序遍历与中序遍历构造二叉树. 注意:你可以假设树中没有重复的元素. 例如,给出 前序遍历 preorder = [3,9,20,15,7]中序遍历 inorder = [9,3,15,20,7]返回如下的二叉树: 3 / \ 9 20 / \ 15 7 1 class Solution: 2 def buildTree(self, preorder, inorder): 3 """ 4 :type preorder: List[int] 5 :type inor

[LeetCode]105. 从前序与中序遍历序列构造二叉树(递归)

题目 根据一棵树的前序遍历与中序遍历构造二叉树. 注意: 你可以假设树中没有重复的元素. 题解 递归 递归传参:该子树对应的前序遍历和中序遍历(用开始结束指针表示即可) 确定每层:new当前子树根节点,左右孩子分别赋值为递归的返回值 递归结束条件:返回当前子树根节点 使用HashMap记录当前子树根节点在中序遍历中的位置,方便每次查找. 利用左子树节点数量查找idx 代码 /** * Definition for a binary tree node. * public class TreeNo