LeetCode 剑指 Offer 55 - I 二叉树的深度

思路:树的深度等于左边树的深度和右边树的深度的最大值+1,所以递归遍历左子树和右子树

树的定义

 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
          }
      }

测试数据

        [3,9,20,null,null,15,7]

       let root : TreeNode = TreeNode(3);
        let node1 : TreeNode = TreeNode(9);
        let node2 : TreeNode = TreeNode(20);
        let node3 : TreeNode = TreeNode(15);
        let node4 : TreeNode = TreeNode(7);
        root.left = node1;
        root.right = node2;
        node2.left = node3;
        node2.right = node4;

具体方法


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


你可能感兴趣的:(LeetCode 剑指 Offer 55 - I 二叉树的深度)