11. 平衡二叉树
var isBalanced = function(root) {
const getDepth = function(node) {
if(node === null) return 0;
let leftDepth = getDepth(node.left);
if(leftDepth === -1) return -1;
let rightDepth = getDepth(node.right);
if(rightDepth === -1) return -1;
if(Math.abs(leftDepth - rightDepth) > 1) {
return -1;
} else {
return 1 + Math.max(leftDepth, rightDepth);
}
}
return !(getDepth(root) === -1);
};
var getHeight = function (curNode) {
let queue = [];
if (curNode !== null) queue.push(curNode);
let depth = 0, res = 0;
while (queue.length) {
let node = queue[queue.length - 1];
if (node !== null) {
queue.pop();
queue.push(node);
queue.push(null);
depth++;
node.right && queue.push(node.right);
node.left && queue.push(node.left);
} else {
queue.pop();
node = queue[queue.length - 1];
queue.pop();
depth--;
}
res = res > depth ? res : depth;
}
return res;
}
var isBalanced = function (root) {
if (root === null) return true;
let queue = [root];
while (queue.length) {
let node = queue[queue.length - 1];
queue.pop();
if (Math.abs(getHeight(node.left) - getHeight(node.right)) > 1) {
return false;
}
node.right && queue.push(node.right);
node.left && queue.push(node.left);
}
return true;
};
12. 二叉树的所有路径
var binaryTreePaths = function(root) {
const paths = [];
const construct_paths = (root, path) => {
if (root) {
path += root.val.toString();
if (root.left === null && root.right === null) {
paths.push(path);
} else {
path += "->";
construct_paths(root.left, path);
construct_paths(root.right, path);
}
}
}
construct_paths(root, "");
return paths;
};
13. 左叶子之和
var sumOfLeftLeaves = function(root) {
const nodesSum = function(node){
if(node===null){
return 0;
}
let leftValue = nodesSum(node.left);
let rightValue = nodesSum(node.right);
let midValue = 0;
if(node.left&&node.left.left===null&&node.left.right===null){
midValue = node.left.val;
}
let sum = midValue + leftValue + rightValue;
return sum;
}
return nodesSum(root);
};