这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战。
二叉树的层序遍历
题目
给你二叉树的根节点 root ,返回其节点值的 层序遍历 。(即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
方法
思路:
- 定义
current存储当前层级的值,定义next存储下一层级的节点; - 遍历
[root]当queue.length为0时,说明当前层级所有节点都已经访问过,结果中保存当前层级的值,然后访问下一层。
代码:
/**
* 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 levelOrder = function(root) {
if(!root) return []
const res = []
let queue = [root]
let current = []
let next = []
while(queue.length > 0 || current.length > 0) {
if(queue.length === 0) {
res.push(current)
queue = next
next = []
current = []
}
let q = queue.shift()
if(q) {
current.push(q.val)
next.push(q.left)
next.push(q.right)
}
}
return res
};
结果:
- 执行结果: 通过
- 执行用时:68 ms, 在所有 JavaScript 提交中击败了83.48%的用户
- 内存消耗:43.1 MB, 在所有 JavaScript 提交中击败了14.82%的用户
- 通过测试用例:34 / 34
二叉树的最大深度
题目
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
解题方法
思路:
递归获取左、右节点的最大深度,取最大值加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) return 0
let leftDepth = maxDepth(root.left)
let rightDepth = maxDepth(root.right)
return Math.max(leftDepth, rightDepth) + 1
};
结果:
- 执行结果: 通过
- 执行用时:60 ms, 在所有 JavaScript 提交中击败了98.06%的用户
- 内存消耗:43.6 MB, 在所有 JavaScript 提交中击败了19.94%的用户
- 通过测试用例:39 / 39
对称二叉树
题目
给你一个二叉树的根节点 root , 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
解题方法
思路:
- 定义辅助方法 check 校验二叉树的坐节点和右节点是否相同;
- 左右节点都为空,则返回
true; - 左右节点有一个为空,则返回
false; - 左右节点的 val 值不相同,则返回
false; - 再递归校验左节点的左节点和右节点的右节点以及左节点的右节点和右节点的左节点是否相同;
- 若上述条件都满足,则证明二叉树是对称二叉树。
代码:
/**
* 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 {boolean}
*/
var isSymmetric = function(root) {
if(!root) return true
return check(root.left, root.right)
};
var check = function(left, right) {
if(left === null && right === null) {
return true
}
if(left === null || right === null) {
return false
}
if(left.val !== right.val) {
return false
}
return check(left.left, right.right) && check(left.right, right.left)
}
结果:
- 执行结果: 通过
- 执行用时:88 ms, 在所有 JavaScript 提交中击败了19.68%的用户
- 内存消耗:43.6 MB, 在所有 JavaScript 提交中击败了17.23%的用户
- 通过测试用例:197 / 197