Created
November 8, 2019 03:10
-
-
Save jabes/9e99ce3012e3eee39f7ff0de278aaf22 to your computer and use it in GitHub Desktop.
Count Visible Nodes in Binary Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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