var invertTree = function(root) {
if(!root) return root
const left = invertTree(root.left)
const right = invertTree(root.right)
root.left = right
root.right = left
return root
};🔄 二刷 2026-09-10:一次通过。纠偏重点:旧版返回
{ val, left, right }对象字面量会丢失TreeNode原型且未在原地修改原树指针;改为标准的原地交换指针。解构单行写法[root.left, root.right] = [invertTree(root.right), invertTree(root.left)]亦可。
var isBalanced = function(root) {
const height = (node) => {
if(!node) return 0
let left = height(node.left)
if(left === -1) return -1
let right = height(node.right)
if(right === -1) return -1
if(Math.abs(left-right)>1) return -1
return Math.max(left, right)+1
}
return height(root) !== -1
};var diameterOfBinaryTree = function(root) {
let max = 0
const dfs = (node) => {
if(!node) return 0
const left = dfs(node.left)
const right = dfs(node.right)
max = Math.max(max, left+right)
return Math.max(left, right) + 1
}
dfs(root)
return max
};相关笔记
var maxDepth = function(root) {
if(!root) return 0
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
};var levelOrder = function(root) {
if(!root) return []
const res = []
const queue = [root]
while(queue.length) {
let len = queue.length
res.push([])
while(len--){
let curr = queue.shift()
res[res.length-1].push(curr.val)
curr.left && queue.push(curr.left)
curr.right && queue.push(curr.right)
}
}
return res
};