• [Swift]LeetCode971.翻转二叉树以匹配先序遍历 | Flip Binary Tree To Match Preorder Traversal


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

    Given a binary tree with N nodes, each node has a different value from {1, ..., N}.

    A node in this binary tree can be flipped by swapping the left child and the right child of that node.

    Consider the sequence of N values reported by a preorder traversal starting from the root.  Call such a sequence of N values the voyage of the tree.

    (Recall that a preorder traversal of a node means we report the current node's value, then preorder-traverse the left child, then preorder-traverse the right child.)

    Our goal is to flip the least number of nodes in the tree so that the voyage of the tree matches the voyagewe are given.

    If we can do so, then return a list of the values of all nodes flipped.  You may return the answer in any order.

    If we cannot do so, then return the list [-1]

    Example 1:

    Input: root = [1,2], voyage = [2,1]
    Output: [-1]
    

    Example 2:

    Input: root = [1,2,3], voyage = [1,3,2]
    Output: [1]
    

    Example 3:

    Input: root = [1,2,3], voyage = [1,2,3]
    Output: [] 

    Note:

    1. 1 <= N <= 100

    给定一个有 N 个节点的二叉树,每个节点都有一个不同于其他节点且处于 {1, ..., N} 中的值。

    通过交换节点的左子节点和右子节点,可以翻转该二叉树中的节点。

    考虑从根节点开始的先序遍历报告的 N 值序列。将这一 N 值序列称为树的行程。

    (回想一下,节点的先序遍历意味着我们报告当前节点的值,然后先序遍历左子节点,再先序遍历右子节点。)

    我们的目标是翻转最少的树中节点,以便树的行程与给定的行程 voyage 相匹配。 

    如果可以,则返回翻转的所有节点的值的列表。你可以按任何顺序返回答案。

    如果不能,则返回列表 [-1]。 

    示例 1:

    输入:root = [1,2], voyage = [2,1]
    输出:[-1]
    

    示例 2:

    输入:root = [1,2,3], voyage = [1,3,2]
    输出:[1]
    

    示例 3:

    输入:root = [1,2,3], voyage = [1,2,3]
    输出:[] 

    提示:

    1. 1 <= N <= 100

    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     var p:Int = 0
    16     var fed:[Int] = [Int]()
    17     func flipMatchVoyage(_ root: TreeNode?, _ voyage: [Int]) -> [Int] {
    18         p = 0
    19         if dfs(root, voyage)
    20         {
    21             return fed
    22         }
    23         else
    24         {
    25             fed = [Int]()
    26             fed.append(-1);
    27             return fed;
    28         }        
    29     }
    30     
    31     func dfs(_ cur: TreeNode?, _ voyage: [Int]) -> Bool
    32     {
    33         if cur == nil {return true}
    34         if voyage[p] != cur!.val {return false}
    35         p += 1
    36         if cur!.left == nil
    37         {
    38             return dfs(cur?.right, voyage)
    39         }
    40         if cur!.right == nil
    41         {
    42             return dfs(cur?.left, voyage)
    43         }
    44         
    45         if voyage[p] == cur!.left!.val
    46         {
    47             var res:Bool = dfs(cur?.left, voyage)
    48             if !res
    49             {
    50                 return false
    51             }
    52             return dfs(cur?.right, voyage)
    53         }
    54         else
    55         {
    56             fed.append(cur!.val)
    57             var res:Bool = dfs(cur?.right, voyage)
    58             if !res
    59             {
    60                 return false
    61             }
    62             return dfs(cur?.left, voyage)
    63         }
    64     }
    65 }

    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     var voyage = [Int]()
    16     var results = [Int]()
    17     var legit = false
    18     
    19     func flipMatchVoyage(_ root: TreeNode?, _ voyage: [Int]) -> [Int] {
    20         self.voyage = voyage
    21         self.results = []
    22         self.legit = true
    23         
    24         helper(root, 0, voyage.count)
    25         
    26         return legit ? results : [-1]
    27     }
    28     
    29     func helper(_ root: TreeNode?, _ start: Int, _ end: Int) -> Int {
    30         guard legit else { return 0 }
    31         guard let root = root else { 
    32             legit = end == start
    33             return 0 
    34         }
    35         guard root.val == voyage[start] else {
    36             legit = false
    37             return 0
    38         }
    39         
    40         if let l = root.left, let r = root.right {
    41             if l.val == voyage[start + 1] {
    42                 var i = start + 1
    43                 while voyage[i] != r.val && i < end {
    44                     i += 1
    45                 }
    46                 
    47                 if i == end {
    48                     legit = false
    49                     return 0
    50                 } else {
    51                     return helper(l, start + 1, i) + helper(r, i, end) + 1
    52                 }
    53             } else if r.val == voyage[start + 1] {
    54                 results.append(root.val)
    55                 var i = start + 1
    56                 while voyage[i] != l.val && i < end {
    57                     i += 1
    58                 }
    59                 
    60                 if i == end {
    61                     legit = false
    62                     return 0
    63                 } else {
    64                     return helper(r, start + 1, i) + helper(l, i, end) + 1
    65                 }
    66             } else {
    67                 legit = false
    68             }
    69             
    70         } else if let l = root.left {
    71             helper(l, start + 1, end) + 1
    72         } else if let r = root.right { 
    73             helper(r, start + 1, end) + 1
    74         } else if end == start + 1 {
    75             return 1
    76         } else {
    77             legit = false
    78             return 0
    79         }
    80         
    81         return 0
    82     }
    83 }

    24ms

     1 class Solution {
     2     func flipMatchVoyage(_ root: TreeNode?, _ voyage: [Int]) -> [Int] {
     3         var res = [Int]()
     4         if root == nil && voyage.count == 0 {
     5             return []
     6         } else if root == nil && voyage.count != 0 {
     7             return [-1]
     8         } else if root != nil && voyage.count == 0 {
     9             return [-1]
    10         } else if root?.val != voyage[0] {
    11             return [-1]
    12         } else {
    13             if root?.left == nil && root?.right == nil {
    14                 return []
    15             } else if root?.left == nil {
    16                 let rvalue = root!.right!.val
    17                 let rvoy = cutArray(voyage, rvalue, -1)
    18                 let rres = flipMatchVoyage(root!.right, rvoy)
    19                 if rres == [-1] {
    20                     res = [-1]
    21                 } else {
    22                     res.append(contentsOf: rres)
    23                 }
    24             } else if root?.right == nil {
    25                 let lvalue = root!.left!.val
    26                 let lvoy = cutArray(voyage, lvalue, -1)
    27                 let lres = flipMatchVoyage(root!.left, lvoy)
    28                 if lres == [-1] {
    29                     res = [-1]
    30                 } else {
    31                     res.append(contentsOf: lres)
    32                 }
    33             } else {
    34                 var ll = root!.left!.val
    35                 var rr = root!.right!.val
    36                 if ll != voyage[1] {
    37                     if rr == voyage[1] {
    38                         let node = root?.left
    39                         root?.left = root?.right
    40                         root?.right = node
    41                         res.append(root!.val)
    42                     } else {
    43                         res = [-1]
    44                         return res
    45                     }
    46                 }
    47                 ll = root!.left!.val
    48                 rr = root!.right!.val
    49                 let lvoy = cutArray(voyage, ll, rr)
    50                 let rvoy = cutArray(voyage, rr, -1)
    51                 let lres = flipMatchVoyage(root!.left!, lvoy)
    52                 let rres = flipMatchVoyage(root!.right!, rvoy)
    53                 if lres == [-1] || rres == [-1] {
    54                     res = [-1]
    55                 } else {
    56                     res.append(contentsOf: lres)
    57                     res.append(contentsOf: rres)
    58                 }
    59             }
    60         }
    61         return res
    62     }
    63     
    64     func cutArray(_ arr: [Int], _ start: Int, _ end: Int) -> [Int] {
    65         var res = [Int]()
    66         var bb = false
    67         for i in arr {
    68             if i == start {
    69                 bb = true
    70             }
    71             if i == end {
    72                 bb = false
    73                 break
    74             }
    75             if bb {
    76                 res.append(i)
    77             }
    78         }
    79         return res
    80     }
    81 }

    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 flipMatchVoyage(_ root: TreeNode?, _ voyage: [Int]) -> [Int] {
    16         if voyage[0] != root?.val {
    17             return [-1]
    18         }
    19         var index = -1
    20         let ans = tryFilp(root!, &index, voyage)
    21         return ans.contains(-1) ? [-1] : ans
    22     }
    23     
    24     func tryFilp(_ node: TreeNode?, _ nodeIndex: inout Int, _ voyage: [Int]) -> [Int] {
    25         guard let node = node else {
    26             return [-1]
    27         }
    28         nodeIndex += 1
    29         if node.val != voyage[nodeIndex] {
    30             return [-1]
    31         }
    32         if node.left == nil && node.right == nil {
    33             return []
    34         }
    35         if node.left != nil || node.right != nil {
    36             if node.left != nil {
    37                 if node.left?.val != voyage[nodeIndex + 1] {
    38                     let temp = node.left
    39                     node.left = node.right
    40                     node.right = temp
    41                     var ans = tryFilp(node.left, &nodeIndex, voyage) + [node.val]
    42                     if node.right != nil {
    43                         ans += tryFilp(node.right, &nodeIndex, voyage)
    44                     }
    45                     return ans
    46                 } else {
    47                     var ans = tryFilp(node.left, &nodeIndex, voyage)
    48                     if node.right != nil {
    49                         ans += tryFilp(node.right, &nodeIndex, voyage)
    50                     }
    51                     return ans
    52                 }
    53             } else {
    54                 if node.right?.val != voyage[nodeIndex + 1] {
    55                     return [-1]
    56                 } else {
    57                     return tryFilp(node.right, &nodeIndex, voyage)
    58                 }
    59             }
    60         }
    61         return []
    62     }
    63 }

    60ms

     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 flipMatchVoyage(_ root: TreeNode?, _ voyage: [Int]) -> [Int] {
    17         guard !voyage.isEmpty else { return [-1] }
    18         guard root?.val == voyage[0] else { return [-1] }
    19         var swaps: [Int] = []
    20         var seenDifferentIndices = Set<Int>()
    21         
    22         while true { 
    23             let preorder = preorderTraversal(of: root)
    24             
    25             if let indexOfDifference = Array(zip(preorder, voyage)).firstIndex(where: { (a, b) in a != b }) {
    26                 let differentValue = preorder[indexOfDifference] 
    27                 let parent = parentNode(of: differentValue, in: root)!
    28                 let left = parent.left
    29                 parent.left = parent.right
    30                 parent.right = left
    31                 swaps.append(parent.val)
    32                 
    33                 if seenDifferentIndices.contains(indexOfDifference) {
    34                     return [-1]
    35                 } 
    36                 seenDifferentIndices.insert(indexOfDifference) 
    37             } else {
    38                 break
    39             } 
    40         }
    41         
    42         let success = preorderTraversal(of: root) == voyage
    43         return success ? swaps : [-1]
    44     }
    45     
    46     private func parentNode(of value: Int, in tree: TreeNode?) -> TreeNode? {
    47         guard let tree = tree else { return nil }
    48         if tree.left?.val == value || tree.right?.val == value {
    49             return tree
    50         }
    51         
    52         return parentNode(of: value, in: tree.left) ?? parentNode(of: value, in: tree.right)
    53     }
    54     
    55     private func preorderTraversal(of tree: TreeNode?) -> [Int] {
    56         guard let tree = tree else { return [] }
    57         return [tree.val] + preorderTraversal(of: tree.left) + preorderTraversal(of: tree.right)
    58     }
    59 }
  • 相关阅读:
    php-Zip打包文件
    PHP命令行类库 climate
    vim 添加块注释
    冒泡排序|插入排序
    PHP-SeasLog安装和使用
    链表
    多线程上下文切换
    竞态与线程安全
    线程的生命周期
    线程创建的两种方法
  • 原文地址:https://www.cnblogs.com/strengthen/p/10228410.html
Copyright © 2020-2023  润新知