
image.png
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
func maxDepth(_ root: TreeNode?) -> Int {
if root == nil{
return 0
}
if root?.left == nil,root?.right == nil{
return 1;
}else{
let leftNum = self.maxDepath(tree: root?.left, max: 2)
let rightNum = self.maxDepath(tree: root?.right, max: 2);
return leftNum > rightNum ? leftNum:rightNum
}
}
func maxDepath(tree: TreeNode?,max: Int) -> Int{
if tree?.left == nil,tree?.right == nil {
return max;
}else{
var leftNum = 0
var rightNum = 0
if tree?.left == nil{
leftNum = max
}else{
let n = maxDepath(tree: tree?.left, max: max + 1)
if n > leftNum{
leftNum = n;
}
}
if tree?.right == nil{
rightNum = max
}else{
let s = maxDepath(tree: tree?.right, max: max + 1)
if s > rightNum{
rightNum = s
}
}
return leftNum > rightNum ? leftNum : rightNum;
}
}
}
网友评论