Last active
August 29, 2015 14:04
-
-
Save ashaindlin/041bbf8f2c3acd2ad117 to your computer and use it in GitHub Desktop.
Discern which elements of a tree are leafs and which are nodes, given only preorder and postorder traversals
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 """Sample tree: | |
_1_ | |
/ | \\ | |
2 3 4 | |
/ \\ \\ | |
5 6 7 | |
/ \\ \\ | |
8 9 10 | |
""" | |
preorder = [1, 2, 3, 5, 8, 9, 6, 10, 4, 7] | |
postorder = [2, 8, 9, 5, 10, 6, 3, 7, 4, 1] | |
label = [None]*11 | |
p = 0 | |
r = 0 | |
while None in label[1:]: | |
while label[postorder[p]] is not None: | |
p += 1 | |
label[postorder[p]] = "Leaf" | |
q = preorder.index(postorder[p]) | |
while r < q: | |
if label[preorder[r]] is None: | |
label[preorder[r]] = "Node" | |
r += 1 | |
for i in range(1, 11): | |
print i, label[i] |
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
Sample tree: | |
_1_ | |
/ | \ | |
2 3 4 | |
/ \ \ | |
5 6 7 | |
/ \ \ | |
8 9 10 | |
1 Node | |
2 Leaf | |
3 Node | |
4 Node | |
5 Node | |
6 Node | |
7 Leaf | |
8 Leaf | |
9 Leaf | |
10 Leaf |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment