104. Maximum Depth of Binary Tree

75 阅读1分钟

题目描述

Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.

Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.

解题思路1: DFS

我们可以使用递归, 对二叉树进行深度遍历, 然后比较左子树的deep和右子树的deep, 这个代码非常简单

示例代码1:

func maxDepth(_ root: TreeNode?) -> Int {
    return root == nil ? 0 : max(maxDepth(root?.left), maxDepth(root?.right)) + 1
}

解题思路2: 辅助栈遍历

二叉树的遍历我们可以使用队列和栈完成, 获取深度, 我们可以使用深度优先(栈)进行遍历, 每遍历一层, 深度+1

func maxDepth(_ root: TreeNode?) -> Int {
    guard let root = root else { return 0 }
    var stack = [[TreeNode]]()
    stack.append([root])
    var deep = 0
    while !stack.isEmpty {
        let last = stack.removeLast()
        if last.count > 0 {
            deep += 1
            var line = [TreeNode]()
            last.forEach { (node) in
                if let left = node.left  {
                    line.append(left)
                }
                if let right = node.right {
                    line.append(right)
                }
            }
            stack.append(line)
        }
    }
    return deep
}