Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. //Univalue subtrees
  2. //Count how many univalue subtrees are in any node within a Binary search tree
  3. //Univalues are when the children of the node are equal to the value of the node, or when the children are both null
  4.  
  5. function countUnivalueSubtrees(root) {
  6. let count = 0;
  7. if(!root) return 0;
  8. is_uni(root, count);
  9. return count;
  10. }
  11. function is_uni(node, count) {
  12. //Base case. If we know that both node children are null, we know the node is a univalue, and can increment count and return true
  13. if(node.left === null && node.right === null) {
  14. count++;
  15. return true;
  16. }
  17.  
  18. //set the boolean automatically to true, check is_uni for each search tree
  19. let is_unival = true;
  20. if(node.left !== null) {
  21. is_unival = is_uni(node.left) && is_unival && (node.left.val === node.val);
  22. }
  23. if(node.right !== null) {
  24. is_unival = is_uni(node.right) && is_unival && (node.right.val === node.val);
  25. }
  26.  
  27. //We need to check if the is_unival is false so we don't run the next line of code where we add the count
  28. if(!is_unival) return false
  29. //If it's true, we want to increment the count, then return true to let the other nodes know
  30. count++;
  31. return true;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement