>[danger]编程:二叉树层数 可以使用**深度优先搜索(DFS)** 或 **广度优先搜索(BFS)** 来找到二叉树的层数。 下面是使用**深度优先搜索**的示例代码: ```javascript class TreeNode { constructor(val, left, right) { this.val = val; this.left = left; this.right = right; } } function findTreeDepth(root) { if (root === null) { return 0; } const leftDepth = findTreeDepth(root.left); const rightDepth = findTreeDepth(root.right); return Math.max(leftDepth, rightDepth) + 1; } // 创建二叉树 const root = new TreeNode( 1, new TreeNode(2, new TreeNode(4), new TreeNode(5)), new TreeNode(3) ); // 求二叉树的层数 const depth = findTreeDepth(root); console.log(depth); // 输出: 3 ``` 在上述代码中,定义了一个 `TreeNode` 类来表示二叉树节点。函数 `findTreeDepth` 使用递归的方式计算二叉树的层数。如果当前节点为空,则返回 0;否则,分别计算左子树和右子树的层数,并返回较大的层数加 1。 这个算法的时间复杂度是 O(n),其中 n 是二叉树的节点数。因为我们需要遍历每个节点一次来计算层数,所以时间复杂度与节点数成正比。 如果你想使用广度优先搜索来计算二叉树的层数,可以借助队列实现层序遍历,并且在遍历每一层时计数。这种方法可以保证先遍历完一层再遍历下一层,也能得到正确的层数。 总之,以上给出了使用深度优先搜索的方法来找到二叉树的层数,并且时间复杂度是 O(n),其中 n 是二叉树的节点数。