0x00 题目
二叉树上有 n
个节点,按从 0
到 n - 1
编号
其中节点 i
的两个子节点分别是 leftChild[i]
和 rightChild[i]
只有 所有
节点能够形成且 只
形成 一颗
有效的二叉树时
返回 true
;否则返回 false
如果节点 i
没有左子节点,那么 leftChild[i]
就等于 -1
右子节点也符合该规则
注意:节点没有值,本问题中仅仅使用节点编号
0x01 思路
首先要找到根
节点
然后再遍历
检查是否有环
0x02 解法
语言:Swift
树节点:TreeNode
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
解法:
func validateBinaryTreeNodes(_ n: Int, _ leftChild: [Int], _ rightChild: [Int]) -> Bool {
// 遍历 2 个数组,统计出现次数
var arr = [Int](repeating: 0, count: n)
for i in 0..<n {
let left = leftChild[i]
if left != -1 {
arr[left] += 1
}
let right = rightChild[i]
if right != -1 {
arr[right] += 1
}
}
// 找到根节点
var root = -1
for i in 0..<n {
if arr[i] == 0 {
root = i
break
}
}
if root == -1 {
return false
}
// 遍历,检查是否有环(一个节点被访问多次)
var count = 0
var queue: [Int] = []
var visited = [Int](repeating: 0, count: n)
queue.append(root)
visited[root] += 1
while !queue.isEmpty {
let node = queue.removeFirst()
count += 1
let left = leftChild[node]
if left != -1 {
visited[left] += 1
if visited[left] > 1 {
return false
}
queue.append(left)
}
let right = rightChild[node]
if right != -1 {
visited[right] += 1
if visited[right] > 1 {
return false
}
queue.append(right)
}
}
// 每次节点都应该遍历到
return count == n
}
0x03 我的小作品
欢迎体验我的作品之一:小编辑器-XCompiler
小巧在线编辑器
App Store
搜索即可~