Created
May 13, 2020 19:47
-
-
Save c02y/403bfb74c56039228f5f3ba0634597c3 to your computer and use it in GitHub Desktop.
TopDownPrintBinaryTree.py
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
# https://cyc2018.github.io/CS-Notes/#/notes/32.1%20%E4%BB%8E%E4%B8%8A%E5%BE%80%E4%B8%8B%E6%89%93%E5%8D%B0%E4%BA%8C%E5%8F%89%E6%A0%91 | |
class Node: | |
def __init__(self, val=0): | |
self.val = val | |
self.left = None | |
self.right = None | |
class TreeNodes: | |
def __init__(self): | |
self.root = None | |
def addNode(self, root, data, index, size): | |
if index < size: | |
temp = Node(data[index]) | |
root = temp | |
root.left = self.addNode(root.left, data, 2 * index + 1, size) | |
root.right = self.addNode(root.right, data, 2 * index + 2, size) | |
return root | |
def PrintFromTopToBottom(self, root): | |
if not root: | |
return [] | |
currentStack = [root] | |
res = [] | |
while currentStack: | |
nextStack = [] | |
for i in currentStack: | |
if i.left: nextStack.append(i.left) | |
if i.right: nextStack.append(i.right) | |
res.append(i.val) | |
currentStack = nextStack | |
return res | |
if __name__ == '__main__': | |
data = [1, 2, 3, 4, 5, 6, 7] | |
tn = TreeNodes() | |
root = tn.addNode(tn, data, 0, len(data)) | |
res = tn.PrintFromTopToBottom(root) | |
print(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
CPP version: