ZhengXingchi / ZhengXingchi.github.io

Apache License 2.0
0 stars 0 forks source link

剑指offer(38)二叉树的深度 #43

Open ZhengXingchi opened 4 years ago

ZhengXingchi commented 4 years ago

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

ZhengXingchi commented 4 years ago

解析

树的深度=左子树的深度和右子树深度中最大者+1

  function deep(root) {
      if (root == null) return 0
      return Math.max(deep(root.left), deep(root.right)) + 1
    }