ปัญหา
รับราก BST คำนวณผลรวมข้อมูลใน Left Leaves (โหนดใบที่เป็นลูกซ้าย)
ตัวอย่าง
BST: 8 / \ 1 10 / \ 5 17
Left leaves: 1 และ 5 → ผลรวม 6
โค้ดตัวอย่าง
class Node{ constructor(data) { this.data = data; this.left = null; this.right = null; } };
class BinarySearchTree{ constructor(){ this.root = null; } insert(data){ ... } insertNode(node, newNode){ ... } };
const BST = new BinarySearchTree();
BST.insert(5); BST.insert(3); BST.insert(6); BST.insert(6); BST.insert(9); BST.insert(4); BST.insert(7);
const isLeaf = node => { if (!node) return false; return (node.left === null && node.right === null); }
const traverseTreeAndSumLeftLeaves = (root, sum = 0) => {
if (!root) return sum;
if (isLeaf(root)) return sum;
if (root.left) {
if (isLeaf(root.left)) { sum += root.left.data; traverseTreeAndSumLeftLeaves(root.left, sum); }
else sum = traverseTreeAndSumLeftLeaves(root.left, sum);
}
if (root.right) {
if (isLeaf(root.right)) return sum;
else { sum = traverseTreeAndSumLeftLeaves(root.right, sum); }
}
return sum;
};
console.log(traverseTreeAndSumLeftLeaves(BST.root));
ผลลัพธ์
7