题目描述
解题思路
方法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;
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。