[Swift]LeetCode993. 二叉树的堂兄弟节点 | Cousins in Binary Tree
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10390643.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
In a binary tree, the root node is at depth 0
, and children of each depth k
node are at depth k+1
.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root
of a binary tree with unique values, and the values x
and y
of two different nodes in the tree.
Return true
if and only if the nodes corresponding to the values x
and y
are cousins.
Example 1:
Input: root = [1,2,3,4], x = 4, y = 3
Output: false
Example 2:
Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true
Example 3:
Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false
Note:
- The number of nodes in the tree will be between
2
and100
. - Each node has a unique integer value from
1
to100
.
在二叉树中,根节点位于深度 0
处,每个深度为 k
的节点的子节点位于深度 k+1
处。
如果二叉树的两个节点深度相同,但父节点不同,则它们是一对堂兄弟节点。
我们给出了具有唯一值的二叉树的根节点 root
,以及树中两个不同节点的值 x
和 y
。
只有与值 x
和 y
对应的节点是堂兄弟节点时,才返回 true
。否则,返回 false
。
示例 1:
输入:root = [1,2,3,4], x = 4, y = 3 输出:false
示例 2:
输入:root = [1,2,3,null,4,null,5], x = 5, y = 4 输出:true
示例 3:
输入:root = [1,2,3,null,4], x = 2, y = 3 输出:false
提示:
- 二叉树的节点数介于
2
到100
之间。 - 每个节点的值都是唯一的、范围为
1
到100
的整数。
Runtime: 12 ms
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 ddd:Int = 0 16 func isCousins(_ root: TreeNode?, _ x: Int, _ y: Int) -> Bool { 17 var px:TreeNode? = dfs(root, nil, x, 0, 1) 18 var py:TreeNode? = dfs(root, nil, y, 0, -1) 19 return x != y && px != nil && py != nil && px!.val != py!.val && ddd == 0 20 } 21 22 func dfs(_ cur:TreeNode?,_ par:TreeNode?,_ x:Int,_ dep:Int,_ mul:Int) -> TreeNode? 23 { 24 if cur == nil {return nil} 25 if cur!.val == x 26 { 27 ddd += dep * mul 28 return par 29 } 30 var res:TreeNode? = dfs(cur!.left, cur, x, dep + 1, mul) 31 if res != nil {return res} 32 res = dfs(cur!.right, cur, x, dep+1, mul) 33 return res 34 } 35 }
18424 kb
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 isCousins(_ root: TreeNode?, _ x: Int, _ y: Int) -> Bool { 16 guard let root = root else { 17 return false 18 } 19 20 var rootVal = -1 21 var cousinLevel = -1 22 var isCousins = false 23 24 func goNext(_ node: TreeNode?, _ level: Int, _ parent: TreeNode) { 25 guard let node = node else { 26 return 27 } 28 29 if node.val == x || node.val == y { 30 if rootVal == -1 { 31 rootVal = parent.val 32 cousinLevel = level 33 } else if rootVal != parent.val && cousinLevel == level { 34 isCousins = true 35 } 36 } 37 38 goNext(node.left, level + 1, node) 39 goNext(node.right, level + 1, node) 40 } 41 42 goNext(root.left, 1, root) 43 goNext(root.right, 1, root) 44 45 return isCousins 46 } 47 }
18504 kb
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 isCousins(_ root: TreeNode?, _ x: Int, _ y: Int) -> Bool { 16 var queue = [TreeNode]() 17 guard let root = root else { 18 return false 19 } 20 21 queue.append(root) 22 while queue.count > 0 { 23 let size = queue.count 24 var level = [Int]() 25 for i in 0..<size { 26 let temp = queue.removeFirst() 27 if let left = temp.left, let right = temp.right { 28 if (left.val == x && right.val == y) || (left.val == y && right.val == x) { 29 return false 30 } 31 queue.append(left) 32 queue.append(right) 33 level.append(left.val) 34 level.append(right.val) 35 } else if let left = temp.left { 36 queue.append(left) 37 level.append(left.val) 38 } else if let right = temp.right{ 39 queue.append(right) 40 level.append(right.val) 41 } 42 } 43 if level.contains(x) && level.contains(y) { 44 return true 45 } 46 } 47 return false 48 } 49 }
18508 kb
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 isCousins(_ root: TreeNode?, _ x: Int, _ y: Int) -> Bool { 16 var depths = [Int:Int]() 17 var parents = [Int:TreeNode]() 18 find(root, val: x, depths: &depths, parents: &parents) 19 find(root, val: y, depths: &depths, parents: &parents) 20 if let xDepth = depths[x], let yDepth = depths[y], let xParent = parents[x], let yParent = parents[y] { 21 return xDepth == yDepth && xParent !== yParent 22 } 23 return false 24 } 25 26 func find(_ node: TreeNode?, val: Int, depth: Int = 0, depths: inout [Int:Int], parents: inout [Int:TreeNode]) { 27 guard let node = node else { 28 return 29 } 30 if let left = node.left, left.val == val { 31 parents[val] = node 32 depths[val] = depth 33 return 34 } 35 else if let right = node.right, right.val == val { 36 parents[val] = node 37 depths[val] = depth 38 return 39 } 40 find(node.left, val: val, depth: depth + 1, depths: &depths, parents: &parents) 41 find(node.right, val: val, depth: depth + 1, depths: &depths, parents: &parents) 42 } 43 }
18636 kb
1 class Solution { 2 private var xVal: Int! 3 private var yVal: Int! 4 5 private var xPair: (lvl: Int, prnt: Int)? 6 private var yPair: (lvl: Int, prnt: Int)? 7 8 func isCousins(_ root: TreeNode?, _ x: Int, _ y: Int) -> Bool { 9 xVal = x 10 yVal = y 11 search(lvl: 0, prevVal: 0, node: root) 12 return xPair?.lvl == yPair?.lvl && xPair?.prnt != yPair?.prnt 13 } 14 15 private func search(lvl: Int, prevVal: Int, node: TreeNode?) { 16 guard let n = node else { return } 17 if n.val == xVal! { 18 xPair = (lvl, prevVal) 19 } else if n.val == yVal! { 20 yPair = (lvl, prevVal) 21 } 22 search(lvl: lvl + 1, prevVal: n.val, node: n.left) 23 search(lvl: lvl + 1, prevVal: n.val, node: n.right) 24 } 25 }
18720 kb
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 isCousins(_ root: TreeNode?, _ x: Int, _ y: Int) -> Bool { 17 let (foundX, foundY, depth) = isCousins(root, 0, x, y) 18 return foundX && foundY && depth != nil 19 } 20 21 func isCousins(_ root: TreeNode?, _ depth: Int, _ x: Int, _ y: Int) -> (foundX: Bool, foundY: Bool, depth: Int?) { 22 guard let root = root else { 23 return (false, false, nil) 24 } 25 26 if root.val == x { 27 return (true, false, depth) 28 } else if root.val == y { 29 return (false, true, depth) 30 } 31 32 var xDepth: Int? = nil 33 var yDepth: Int? = nil 34 35 let (leftFoundX, leftFoundY, leftDepth) = isCousins(root.left, depth + 1, x, y) 36 37 if leftFoundX && leftFoundY { 38 return (leftFoundX, leftFoundY, leftDepth) 39 } 40 41 xDepth = (leftFoundX) ? leftDepth : xDepth 42 yDepth = (leftFoundY) ? leftDepth : yDepth 43 44 let (rightFoundX, rightFoundY, rightDepth) = isCousins(root.right, depth + 1, x, y) 45 46 if rightFoundX && rightFoundY { 47 return (rightFoundX, rightFoundY, rightDepth) 48 } 49 50 xDepth = (rightFoundX) ? rightDepth : xDepth 51 yDepth = (rightFoundY) ? rightDepth : yDepth 52 53 let foundX = leftFoundX || rightFoundX 54 let foundY = leftFoundY || rightFoundY 55 if foundX && foundY { 56 if xDepth == yDepth && (xDepth != (depth+1)) { 57 return (true, true, xDepth) 58 } else { 59 return (true, true, nil) 60 } 61 } else { 62 return (foundX, foundY, xDepth ?? yDepth) 63 } 64 } 65 }
18740 kb
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 protocol Queue { 15 associatedtype T 16 var count: Int { get } 17 var isEmpty: Bool { get } 18 var top: T? { get } 19 func enqueue(_ item: T) 20 func dequeue() -> T? 21 } 22 23 class LinkedListNode<T> { 24 var value: T 25 var next: LinkedListNode<T>? 26 init(_ value: T) { 27 self.value = value 28 } 29 init(_ value: T, _ next: LinkedListNode<T>) { 30 self.value = value 31 self.next = next 32 } 33 } 34 35 class LinkedQueue<Type> : Queue { 36 typealias T = Type 37 private var head: LinkedListNode<T>? 38 private var tail: LinkedListNode<T>? 39 private(set) var count: Int = 0 40 var isEmpty: Bool { 41 return head == nil 42 } 43 var top: T? { 44 return head?.value 45 } 46 47 init () { 48 self.head = nil 49 self.tail = nil 50 } 51 init(_ initialValue: T) { 52 self.head = LinkedListNode<T>(initialValue) 53 self.tail = self.head 54 } 55 56 func enqueue(_ item: T) { 57 if isEmpty { 58 self.tail = LinkedListNode<T>(item) 59 self.head = self.tail 60 } else { 61 self.tail!.next = LinkedListNode<T>(item) 62 self.tail = self.tail!.next 63 } 64 count += 1 65 } 66 67 func dequeue() -> Type? { 68 if let validHead = self.head { 69 let data = validHead.value 70 self.head = validHead.next 71 count -= 1 72 return data 73 } else { 74 return nil 75 } 76 } 77 } 78 79 80 class Solution { 81 func isCousins(_ root: TreeNode?, _ x: Int, _ y: Int) -> Bool { 82 var xParent: Int? = nil 83 var yParent: Int? = nil 84 var xDepth: Int? = nil 85 var yDepth: Int? = nil 86 87 typealias Level = Int 88 let frontier = LinkedQueue<(TreeNode, Level, TreeNode?)>() 89 frontier.enqueue((root!, 0, nil)) 90 91 while true { 92 guard let (node, level, parent) = frontier.dequeue() else { 93 break 94 } 95 if node.val == x { 96 xParent = parent?.val 97 xDepth = level 98 } 99 if node.val == y { 100 yParent = parent?.val 101 yDepth = level 102 } 103 if let leftChild = node.left { 104 frontier.enqueue((leftChild, level + 1, node)) 105 } 106 107 if let rightChild = node.right { 108 frontier.enqueue((rightChild, level + 1, node)) 109 } 110 } 111 112 return (xDepth != nil) && (yDepth != nil) && (xDepth == yDepth) && (xParent != yParent) 113 } 114 }
18776 kb
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 xParent = -1 16 var yParent = -1 17 var xDepth = Int.min 18 var yDepth = Int.max 19 20 func isCousins(_ root: TreeNode?, _ x: Int, _ y: Int) -> Bool { 21 if let r = root { 22 countDepth(r, r.left, x, y, 1) 23 countDepth(r, r.right, x, y, 1) 24 if xParent != yParent && xDepth == yDepth { 25 return true 26 } 27 } 28 return false 29 } 30 31 func countDepth(_ parent: TreeNode, _ node: TreeNode?, _ x: Int, _ y: Int, _ depth: Int) { 32 if let r = node { 33 if r.val == x { 34 xParent = parent.val 35 xDepth = depth 36 } 37 38 if r.val == y { 39 yParent = parent.val 40 yDepth = depth 41 } 42 43 countDepth(r, r.left, x, y, depth+1) 44 countDepth(r, r.right, x, y, depth+1) 45 } 46 } 47 }
18812 kb
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 xNode: (Int, TreeNode?)? 16 var yNode: (Int, TreeNode?)? 17 func isCousins(_ root: TreeNode?, _ x: Int, _ y: Int) -> Bool { 18 helper(root, nil, x, y, 0) 19 guard let xNode = xNode, let yNode = yNode else { return false } 20 return xNode.0 == yNode.0 && xNode.1 !== yNode.1 21 } 22 23 private func helper(_ root: TreeNode?, _ parent: TreeNode?, _ x: Int, _ y: Int, _ depth: Int) { 24 guard let root = root else { return } 25 if root.val == x { 26 xNode = (depth, parent) 27 } 28 if root.val == y { 29 yNode = (depth, parent) 30 } 31 helper(root.left, root, x, y, depth + 1) 32 helper(root.right, root, x, y, depth + 1) 33 } 34 }