开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第16天,点击查看活动详情
1.平衡二叉树
题目描述
解题思路
本题还是采用递归法解决,递归三要素:
1.确认递归参数及返回值,参数仍然为节点,返回值为是否是平衡
2.确认递归终止条件,仍然使用节点为空判断作为终止判断
3.确认单层逻辑,分别求出当前节点的左右子树的高度,如果左右子树高度差大于1,则将其子树高度设置为-1
4.判断最后返回的二叉树高度是否为-1
var isBalanced = function(root) {
var getDepDis = function(node) {
if(node === null) return 0
let leftDep = getDepDis(node.left)
if(leftDep == -1) return -1 // 高度差大于1时 直接返回-1
let rightDep = getDepDis(node.right)
if(rightDep == -1) return -1 // 高度差大于1时 直接返回-1
let result = 0;
if(Math.abs(leftDep - rightDep) > 1){
result = -1
} else {
result = 1 + Math.max(leftDep,rightDep) // 返回二叉树高度
}
return result
}
return getDepDis(root) !== -1
};
2.二叉树的所有路径
题目描述
解题思路
本题同样使用递归法:
1.确认递归参数及返回值,参数为节点及当前路劲值
2.确认递归终止条件,当前节点左右节点为空时,将当前路径添加到结果集中
3.确认单层递归逻辑,将当前节点值和拼接符号添加到当前路径中
var binaryTreePaths = function(root) {
//递归遍历+递归三部曲
let res = [];
//1. 确定递归函数 函数参数
const getPath = function(node,curPath) {
//2. 确定终止条件,到叶子节点就终止
if(node.left === null && node.right === null) {
curPath += node.val;
res.push(curPath);
return;
}
//3. 确定单层递归逻辑
curPath += node.val + '->';
node.left && getPath(node.left, curPath);
node.right && getPath(node.right, curPath);
}
getPath(root, '');
return res;
};
3.所有左子叶之和
题目描述
解题思路
递归判断左右子树的左子节点,符合条件的节点添加到结果中。
var sumOfLeftLeaves = function(root) {
if(root == null) return 0 // 终止条件
let leftVal = sumOfLeftLeaves(root.left) // 单层逻辑
let rightVal = sumOfLeftLeaves(root.right)
let midVal = 0
if(root.left && !root.left.left && !root.left.right) { // 判断左子节点
midVal = root.left.val
}
return leftVal + rightVal + midVal
};