题目
题目链接:leetcode-cn.com/leetbook/re…
题解
1、使用后序遍历递归方法
熟练二叉树的先序遍历、中序遍历、后序遍历的解法,所有这类题目都是由三者为基础可以进行求解的;
/**
* 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}
*/
var maxDepth = function(root) {
// 使用后续遍历递归方法完成
if(root === null) {
return 0;
}
const lMaxDepth = maxDepth(root.left);
const rMaxDepth = maxDepth(root.right);
return lMaxDepth > rMaxDepth ? lMaxDepth + 1 : rMaxDepth + 1;
};
1、使用层次遍历
层次遍历,需要借助队列;下面在层次遍历的基础上改造:
当每一层遍历完了后在队列里插入一个分层标识,并使用一个全局变量记录层数,碰到分层标识就将层数加一,最后得到树的层数,树的层数就是最大深度;
/**
* 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}
*/
var maxDepth = function(root) {
if(root === null) {
return 0;
}
let nodeQueue = [];
let maxDep = 0;
let temp = root;
nodeQueue.push(temp);
nodeQueue.push(0);
while(nodeQueue.length !== 0) {
temp = nodeQueue.shift();
// 判断是否是分层标识
if(temp === 0) {
maxDep ++;
if(nodeQueue.length !== 0) {
nodeQueue.push(0);
}
continue;
}
// 常规层次遍历的代码
if(temp.left !== null) {
nodeQueue.push(temp.left);
}
if(temp.right !== null) {
nodeQueue.push(temp.right);
}
}
return maxDep;
};
二叉树的经典内容当然是其先序遍历、中序遍历、后序遍历的递归和非递归实现,层次遍历,我决定用 JS 把这几个内容都实现一下
二叉树的遍历归总文章在这里:juejin.cn/post/702405…
大家如果有更好的思路和解法,欢迎大家一起来讨论啊~
这是使用 JavaScript 对 LeetCode《初级算法》的每道题的总结和实现的其中一篇,汇总篇在这里: