博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Level Order Tree Traversal
阅读量:4029 次
发布时间:2019-05-24

本文共 4405 字,大约阅读时间需要 14 分钟。

Level Order Tree Traversal

Level order traversal of a tree is or the tree.

Example Tree

Example Tree

Level order traversal of the above tree is 1 2 3 4 5 

METHOD 1 (Use function to print a given level)

Algorithm:

There are basically two functions in this method. One is to print all nodes at a given level (printGivenLevel), and other is to print level order traversal of the tree (printLevelorder). printLevelorder makes use of printGivenLevel to print nodes at all levels one by one starting from root.

/*Function to print level order traversal of tree*/printLevelorder(tree)for d = 1 to height(tree)   printGivenLevel(tree, d);/*Function to print all nodes at a given level*/printGivenLevel(tree, level)if tree is NULL then return;if level is 1, then    print(tree->data);else if level greater than 1, then    printGivenLevel(tree->left, level-1);    printGivenLevel(tree->right, level-1);

Implementation:

  • c
  • Java
  • Python
# Recursive Python program for level order traversal of Binary Tree# A node structureclass Node:    # A utility function to create a new node    def __init__(self, key):        self.data = key         self.left = None        self.right = None# Function to  print level order traversal of treedef printLevelOrder(root):    h = height(root)    for i in range(1, h+1):        printGivenLevel(root, i)# Print nodes at a given leveldef printGivenLevel(root , level):    if root is None:        return    if level == 1:        print "%d" %(root.data),    elif level > 1 :        printGivenLevel(root.left , level-1)        printGivenLevel(root.right , level-1)""" Compute the height of a tree--the number of nodes    along the longest path from the root node down to    the farthest leaf node"""def height(node):    if node is None:        return 0     else :        # Compute the height of each subtree         lheight = height(node.left)        rheight = height(node.right)        #Use the larger one        if lheight > rheight :            return lheight+1        else:            return rheight+1# Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)print "Level order traversal of binary tree is -"printLevelOrder(root)#This code is contributed by Nikhil Kumar Singh(nickzuck_007)

Output:
Level order traversal of binary tree is - 1 2 3 4 5

Time Complexity: O(n^2) in worst case. For a skewed tree, printGivenLevel() takes O(n) time where n is the number of nodes in the skewed tree. So time complexity of printLevelOrder() is O(n) + O(n-1) + O(n-2) + .. + O(1) which is O(n^2).

METHOD 2 (Use Queue)

Algorithm:

For each node, first the node is visited and then it’s child nodes are put in a FIFO queue.

printLevelorder(tree)1) Create an empty queue q2) temp_node = root /*start from root*/3) Loop while temp_node is not NULL    a) print temp_node->data.    b) Enqueue temp_node’s children (first left then right children) to q    c) Dequeue a node from q and assign it’s value to temp_node

Implementation:

Here is a simple implementation of the above algorithm. Queue is implemented using an array with maximum size of 500. We can implement queue as linked list also.

  • C
  • C++
  • Java
  • Python
# Python program to print level order traversal using Queue# A node structureclass Node:    # A utility function to create a new node    def __init__(self ,key):        self.data = key        self.left = None        self.right = None# Iterative Method to print the height of binary treedef printLevelOrder(root):    # Base Case    if root is None:        return        # Create an empty queue for level order traversal    queue = []    # Enqueue Root and initialize height    queue.append(root)    while(len(queue) > 0):        # Print front of queue and remove it from queue        print queue[0].data,        node = queue.pop(0)        #Enqueue left child        if node.left is not None:            queue.append(node.left)        # Enqueue right child        if node.right is not None:            queue.append(node.right)#Driver Program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)print "Level Order Traversal of binary tree is -"printLevelOrder(root)#This code is contributed by Nikhil Kumar Singh(nickzuck_007)

Output:
Level order traversal of binary tree is - 1 2 3 4 5

Time Complexity: O(n) where n is number of nodes in the binary tree

转载地址:http://yphbi.baihongyu.com/

你可能感兴趣的文章
final 的作用
查看>>
在Idea中使用Eclipse编译器
查看>>
idea讲web项目部署到tomcat,热部署
查看>>
优化IDEA启动速度,快了好多。后面有什么优化点,会继续往里面添加
查看>>
JMeter 保持sessionId
查看>>
IDEA Properties中文unicode转码问题
查看>>
Idea下安装Lombok插件
查看>>
zookeeper
查看>>
Idea导入的工程看不到src等代码
查看>>
技术栈
查看>>
Jenkins中shell-script执行报错sh: line 2: npm: command not found
查看>>
8.X版本的node打包时,gulp命令报错 require.extensions.hasownproperty
查看>>
Jenkins 启动命令
查看>>
Maven项目版本继承 – 我必须指定父版本?
查看>>
Maven跳过单元测试的两种方式
查看>>
通过C++反射实现C++与任意脚本(lua、js等)的交互(二)
查看>>
利用清华镜像站解决pip超时问题
查看>>
[leetcode BY python]1两数之和
查看>>
微信小程序开发全线记录
查看>>
Centos import torchvision 出现 No module named ‘_lzma‘
查看>>