Last active
April 3, 2020 02:53
-
-
Save nhudinhtuan/30b72096ef1ac0900ebc8f7214199da8 to your computer and use it in GitHub Desktop.
Tree traversal - level order
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
# Definition for a binary tree node. | |
# class TreeNode(object): | |
# def __init__(self, x): | |
# self.val = x | |
# self.left = None | |
def levelorder_traversal_recursive(root): | |
result = [] | |
def recur(node, level): | |
# base case: | |
if not node: | |
return | |
# start a new level array | |
if len(result) == level: | |
result.append([]) | |
# append the current node value | |
result[level].append(node.val) | |
# process child nodes for the next level from left to right | |
recur(node.left, level + 1) | |
recur(node.right, level + 1) | |
recur(root, 0) | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment