Created
October 14, 2015 18:59
-
-
Save akaila/df65dccac5cc0fc0ba2c to your computer and use it in GitHub Desktop.
This file contains 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
// Print the nodes of binary tree column wise | |
/* | |
Input: | |
8 | |
/ \ | |
6 10 | |
/ \ / \ | |
4 7 9 12 | |
/ \ | |
3 5 | |
Output: | |
3 | |
4 | |
6 5 | |
8 7 9 | |
10 | |
12 | |
*/ | |
function insertInColumns(root, index, hash, min, max) { | |
if (!root) { | |
return { | |
min: min, | |
max: max | |
}; | |
} | |
hash[index] = hash[index] || []; | |
hash[index].push(root.value); | |
var leftResult = insertInColumns(root.left, index-1, hash, min, max); | |
var rightResult = insertInColumns(root.right, index+1, hash, min, max); | |
return { | |
min: Math.min(index, Math.min(leftResult.min, rightResult.min)), | |
max: Math.max(index, Math.max(leftResult.max, rightResult.max)) | |
}; | |
} | |
var tree = { | |
value: 8, | |
left: { | |
value: 6, | |
left: { | |
value: 4, | |
left: { | |
value: 3 | |
}, | |
right: { | |
value: 5 | |
} | |
}, | |
right: { | |
value: 7 | |
} | |
}, | |
right: { | |
value: 10, | |
left: { | |
value: 9 | |
}, | |
right: { | |
value: 12 | |
} | |
} | |
}; | |
var hash = {}; | |
var result = insertInColumns(tree, 0, hash, 0, 0); | |
var output = ""; | |
for (var i = result.min; i <= result.max; i++) { | |
var values = hash[i]; | |
if (!values) { | |
continue; | |
} | |
var str = ""; | |
for (var j = 0; j < values.length; j++) { | |
str += ((j > 0) ? " " : "") + values[j]; | |
} | |
output += str + ((i < result.max) ? "\n" : ""); | |
} | |
console.log(output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment