Created
May 17, 2018 02:44
-
-
Save lttzzlll/a34b06661318740e34230171c6232e9e 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
import unittest | |
class Node: | |
def __init__(self, val): | |
self.val = val | |
self.left = None | |
self.right = None | |
def __str__(self): | |
return self.val | |
class NodeWrapper: | |
def __init__(self, node, level): | |
self.node = node | |
self.level = level | |
def __str__(self): | |
return '{}-{}'.format(self.node, self.level) | |
def left_visit(root): | |
res = [] | |
que = [] | |
lastLevel = 0 | |
que.append(NodeWrapper(root, lastLevel + 1)) | |
while que: | |
nw = que.pop(0) | |
if nw.level > lastLevel: | |
res.append(nw.node.val) | |
lastLevel = nw.level | |
if nw.node.left: | |
que.append(NodeWrapper(nw.node.left, lastLevel + 1)) | |
if nw.node.right: | |
que.append(NodeWrapper(nw.node.right, lastLevel + 1)) | |
return res | |
class LeftVisitTest(unittest.TestCase): | |
@staticmethod | |
def create_tree(): | |
root = Node(1) | |
root.left = Node(2) | |
root.right = Node(3) | |
root.left.left = Node(4) | |
root.left.right = Node(5) | |
root.right.left = Node(6) | |
root.right.right = Node(7) | |
root.right.right.right = Node(8) | |
return root | |
def setUp(self): | |
self.root = LeftVisitTest.create_tree() | |
def test_left_vist(self): | |
res = [1, 2, 4, 8] | |
left_visit_node = left_visit(self.root) | |
self.assertListEqual(res, left_visit_node) | |
print(left_visit_node) | |
def tearDown(self): | |
self.root = None | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
给定一棵二叉树,将其平放到桌面上,只打印从左侧看到的节点。
利用二叉树的层次遍历,从上到下,从左到右,每层只打印第一个节点。