美文网首页
104. 二叉树的最大深度 leetcode

104. 二叉树的最大深度 leetcode

作者: 出来遛狗了 | 来源:发表于2018-11-02 11:13 被阅读2次
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;
        }
    }
}

相关文章

网友评论

      本文标题:104. 二叉树的最大深度 leetcode

      本文链接:https://www.haomeiwen.com/subject/hyvqxqtx.html