Advertisement
Guest User

Untitled

a guest
Apr 29th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. class Node {
  2. constructor(value, left = null, right = null) {
  3. this.value = value;
  4. this.left = left;
  5. this.right = right;
  6. }
  7. }
  8.  
  9. // 40
  10. // / \
  11. // 20 60
  12. // / \ / \
  13. // 10 30 50 70
  14. // Result: 4
  15.  
  16. function getLeafCountOfBinaryTree(node) {
  17. if(node === null) return 0;
  18. if(node.left === null && node.right === null) return 1;
  19. return getLeafCountOfBinaryTree(node.left) + getLeafCountOfBinaryTree(node.right);
  20. }
  21.  
  22.  
  23. let rootNode =new Node(40);
  24. let node20=new Node(20);
  25. let node10=new Node(10);
  26. let node30=new Node(30);
  27. let node60=new Node(60);
  28. let node50=new Node(50);
  29. let node70=new Node(70);
  30.  
  31. rootNode.left=node20;
  32. rootNode.right=node60;
  33.  
  34. node20.left=node10;
  35. node20.right=node30;
  36.  
  37. node60.left=node50;
  38. node60.right=node70;
  39.  
  40. console.log(getLeafCountOfBinaryTree(rootNode));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement