题目描述
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
代码片
/*
* @lc app=leetcode.cn id=104 lang=javascript
*
* [104] 二叉树的最大深度
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
//方法一:广度优先搜索的代码实现1
var maxDepth = function(root) {
if(root == null) return 0;
let queue = [];
queue.push(root);
let ans = 0;
while(queue.length) {
let size = queue.length;
for(let i = 0; i < size; i++) {
//队头出队列
let node = queue.shift();
if(node.left) queue.push(node.left);
if(node.right) queue.push(node.right);
}
ans += 1;
}
return ans;
};
// @lc code=end
//方法二:深度优先搜索
var maxDepth = function (root) {
//定义:输入一个节点,返回以该节点为根的二叉树的最大深度
if(root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}