Swift-二叉树的最大深度与最小深度

题目:输入一棵二叉树的根节点,求该树的深度。从根节点到叶子结点一次经过的结点形成树的一条路径,最长路径的长度为树的深度。根节点的深度为1.

最大深度

`

func treeMaxDepth(rootNode:TreeNode?) -> Int {
    if rootNode == nil {
        return 0
    }
    
    let leftDepth:Int = treeMaxDepth(rootNode: rootNode?.leftChild)
    let rightDepth:Int = treeMaxDepth(rootNode: rootNode?.rightChild)
    
    return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1
}`

最小深度

最小深度: 从根节点开始到叶子节点结束的最短路径上的节点数,递归解决过程:
①空树最小深度是0.
②左子树空: 右子树最小深度+ 1
③右子树空: 左子树最小深度 + 1
④min(左子树最小深度,右子树最小深度) + 1

`
func treeMinDepth(rootNode:TreeNode?) -> Int {
if rootNode == nil {
return 0
}

    let leftDepth:Int = treeMinDepth(rootNode: rootNode?.leftChild)
    let rightDepth:Int = treeMinDepth(rootNode: rootNode?.rightChild)
    
    if leftDepth == 0 {
        return rightDepth + 1
    }
    
    if rightDepth == 0 {
        return leftDepth + 1
    }
    
    return leftDepth < rightDepth ? leftDepth + 1 : rightDepth + 1
}`

测试代码:

`

var util:TreeUtil = TreeUtil()
var depthData:[String] = ["1","2","4","#","#","5","7","#","#","#","3","#","6","#","#"]
var preRootNode:TreeNode?
util.createTreeByPreOrderData(root: &preRootNode, listData: depthData)
var binaryTreePath:BinaryTreePath = BinaryTreePath()
var binaryDepth:Int = binaryTreePath.treeMaxDepth(rootNode: preRootNode)
print("FlyElephant-最大深度--(binaryDepth)")

var binaryMinDepth:Int = binaryTreePath.treeMinDepth(rootNode: preRootNode)
print("FlyElephant-最小深度--(binaryMinDepth)")`

你可能感兴趣的:(Swift-二叉树的最大深度与最小深度)