用 JavaScript 查詢 BST 左葉子的和
問題
我們要求編寫一個 JavaScript 函式,該函式將二叉搜尋樹的根作為唯一引數。
函式應簡單計算儲存在 BST 左葉子中的資料的總和。
例如,如果樹形結構如下所示 −
8 / \ 1 10 / \ 5 17
那麼輸出應如下所示 −
const output = 6;
輸出說明
因為樹中有兩個左葉子,值分別為 1 和 5。
示例
程式碼如下 −
class Node{
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
};
};
class BinarySearchTree{
constructor(){
// root of a binary seach tree
this.root = null;
}
insert(data){
var newNode = new Node(data);
if(this.root === null){
this.root = newNode;
}else{
this.insertNode(this.root, newNode);
};
};
insertNode(node, newNode){
if(newNode.data < node.data){
if(node.left === null){
node.left = newNode;
}else{
this.insertNode(node.left, newNode);
};
} else {
if(node.right === null){
node.right = newNode;
}else{
this.insertNode(node.right,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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP