在 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(){
      //二叉搜索树的根
     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
