Skip to content

Instantly share code, notes, and snippets.

@jabes
Created November 8, 2019 03:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jabes/9e99ce3012e3eee39f7ff0de278aaf22 to your computer and use it in GitHub Desktop.
Save jabes/9e99ce3012e3eee39f7ff0de278aaf22 to your computer and use it in GitHub Desktop.
Count Visible Nodes in Binary Tree
// Question: In a binary tree, if in the path from root to the node A, there is no node with greater value than A’s, this node A is visible.
// We need to count the number of visible nodes in a binary tree.
// For example, in the following tree:
//
// 5
// / \
// 3 10
// / \ /
// 20 21 1
//
// There are four (4) visible nodes: 5, 20, 21, and 10.
function solution(T) {
return traverseTree(-1, -1, T);
}
function traverseTree(nVisibleNodes, parentNodeValue, node) {
let n = 0;
if (node.x > parentNodeValue) nVisibleNodes += 1;
if (null !== node.l) n += traverseTree(nVisibleNodes, node.x, node.l);
if (null !== node.r) n += traverseTree(nVisibleNodes, node.x, node.r);
nVisibleNodes += n;
return nVisibleNodes;
}
const binaryTree = {
x: 5,
l: {
x: 3,
l: {
x: 20,
l: null,
r: null,
},
r: {
x: 21,
l: null,
r: null,
},
},
r: {
x: 10,
l: {
x: 1,
l: null,
r: null,
},
r: null,
},
};
solution(binaryTree);
@kushwanth22
Copy link

kushwanth22 commented May 9, 2021

Hi Justin,
please try for this inputs:
[3,1,4,3, null,1,5] expected:4 but showing 5
[3,3,null,4,2] expected: 3 but sowing 1
[1] expected: 1 but showing 0
not working

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment