题目描述
解题思路
方法1: 遍历
- 找出每层节点,保存在临时数组中
- 一层遍历完保存在结果数组中
- 返回结果数组长度
方法2:递归
返回左右子树的最大值即可
代码实现
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if (!root) return 0;
let res = [];
let queue = [root];
while (queue.length) {
let temp = [];
let size = queue.length;
for (let i=0; i<size; i++) {
let node = queue.shift();
temp.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
};
res.push(temp);
};
console.log(res)
return res.length;
};
方法2:
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if (!root) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};