三道題都沒想出來,還是要加強遞迴的練習
110.平衡二叉樹 (優先掌握遞迴)
再一次涉及到,什麼是高度,什麼是深度,可以鞏固一下。
題目連結/文章講解/影片講解:https://programmercarl.com/0110.平衡二叉樹.html
function getHeight(node) {
if (node === null) return 0;
let leftHeight = 0;
let rightHeight = 0;
leftHeight = getHeight(node.left);
if (leftHeight === -1) {
return -1
}
rightHeight = getHeight(node.right);
if (rightHeight === -1) {
return -1;
}
if (Math.abs(leftHeight - rightHeight)>1) {
return -1;
}
return Math.max(leftHeight,rightHeight) + 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 {boolean}
*/
var isBalanced = function(root) {
let height = getHeight(root);
if (height === -1) {
return false;
}
return true;
};
- 二叉樹的所有路徑 (優先掌握遞迴)
這是大家第一次接觸到回溯的過程, 我在影片裡重點講解了 本題為什麼要有回溯,已經回溯的過程。
如果對回溯 似懂非懂,沒關係, 可以先有個印象。
題目連結/文章講解/影片講解:https://programmercarl.com/0257.二叉樹的所有路徑.html
遞迴加回溯
function getAllPath(node, path, results) {
path.push(node.val);
if (node.left === null && node.right === null) {
let sPath = '';
for (let i=0;i<path.length-1; i++) {
sPath += path[i];
sPath += '->';
}
sPath += path[path.length - 1];
results.push(sPath);
return;
}
if (node.left) {
getAllPath(node.left, path, results);
path.pop();
}
if (node.right) {
getAllPath(node.right, path, results);
path.pop();
}
}
/**
* 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 {string[]}
*/
var binaryTreePaths = function(root) {
const path = [];
const results = [];
getAllPath(root, path, results);
return results;
};
404.左葉子之和 (優先掌握遞迴)
其實本題有點文字遊戲,搞清楚什麼是左葉子,剩下的就是二叉樹的基本操作。
題目連結/文章講解/影片講解:https://programmercarl.com/0404.左葉子之和.html
遞迴
/**
* 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 sumOfLeftLeaves = function(root) {
if (root == null) return 0;
if (root.left === null && root.right === null) return 0;
let leftTol = sumOfLeftLeaves(root.left);
if (root.left && root.left.left === null && root.left.right === null) {
leftTol = root.left.val;
}
leftTol += sumOfLeftLeaves(root.right);
return leftTol;
};