Swift - Binary Tree Maximum Depth: Error Resolution and Code Explanation
This code calculates the maximum depth of a binary tree in Swift. It initially encounters an error because the TreeNode type is not defined within the code snippet. This article explains how to resolve this error and provides a corrected code snippet.
Error Resolution
The error occurs because the code snippet uses the TreeNode class without defining it. To resolve this, we need to define the TreeNode class within the code. Here is the corrected code:
class TreeNode {
var val: Int
var left: TreeNode?
var right: TreeNode?
init() {
self.val = 0
self.left = nil
self.right = nil
}
init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
class Solution {
func maxDepth(_ root: TreeNode?) -> Int {
if root == nil {
return 0
}
return max(maxDepth(root?.left), maxDepth(root?.right)) + 1
}
}
Explanation of TreeNode Definition
The TreeNode class defines the structure of a node in a binary tree. It has three properties:
val: An integer representing the value stored in the node.left: A reference to the left child node. It is of typeTreeNode?(optional) to allow for the possibility of the left child being absent.right: A reference to the right child node. It is also of typeTreeNode?(optional) to allow for the possibility of the right child being absent.
The TreeNode class also provides three initializers:
init(): This initializes a new node with a value of 0 and no children.init(_ val: Int): This initializes a new node with the specified value and no children.init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?): This initializes a new node with the specified value, left child, and right child.
Understanding the Code
The maxDepth() function in the Solution class calculates the maximum depth of the binary tree represented by the root node. The code works recursively by traversing the tree and comparing the depth of the left subtree with the depth of the right subtree. It then returns the maximum depth plus 1 (for the current node). The base case for the recursion is when the root is nil, in which case the depth is 0.
By defining the TreeNode class and understanding the recursive nature of the maxDepth() function, we can effectively calculate the maximum depth of a binary tree in Swift.
原文地址: https://www.cveoy.top/t/topic/qfll 著作权归作者所有。请勿转载和采集!