Python implements two methods for hierarchical traversal of binary tree and output by layer (reproduced)

      版权声明:本文为博主原创文章,未经博主允许不得转载。          https://blog.csdn.net/songyunli1111/article/details/81706801        </div>
        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-cd6c485e8b.css">
                          <div id="content_views" class="markdown_views">
        <!-- flowchart 箭头图标 勿删 -->
        <svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
          <path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>
        </svg>
        <h4 id="二叉树的层次遍历">二叉树的层次遍历</h4>

The hierarchical traversal of a binary tree is to print the nodes of the tree sequentially from top to bottom and from left to right.
The idea is to add the nodes of the binary tree to the queue, and at the same time, the non-empty left and right children are added to the queue in turn, and the traversal is completed when the queue is empty.

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        outList=[]
        queue=[root]
        while queue!=[] and root:
            outList.append(queue[0].val)
            if queue[0].left!=None:
                queue.append(queue[0].left)
            if queue[0].right!=None:
                queue.append(queue[0].right)
            queue.pop(0)
        return outList
 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

In python, the queue is simulated with a list, where the operation complexity of pop(0) is O(n), and the queue is not used as an improvement below.

    def PrintFromTopToBottom(self, root):
        if not root:
            return []
        currentStack = [root]
        outList= []
        while currentStack:
            nextStack = []
            for point in currentStack:
                if point.left: 
                    nextStack.append(point.left)
                if i.right: 
                    nextStack.append(point.right)
                outList.append(point.val)
            currentStack = nextStack
        return outList
 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

Layer-wise output of a binary tree

The layer-by-layer output of a binary tree is to print the nodes of the tree from top to bottom and from left to right. Each layer outputs one line.

The difference between this question and the previous question is mainly to distinguish each layer, that is, not only to traverse by layer but also to output by layer. The difficulty is that some layers will be missing items, that is, not a complete binary tree. However, according to the characteristics of layer traversal, nodes will enter the queue in order by layer, and use this characteristic to distinguish each layer.

The improved version of the above problem is stored in each list by layer, which is also suitable for solving this problem

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回二维列表[[0],[1,2],[4,5]]
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        queue=[pRoot]
        outList=[]
        while queue:
            res=[]
            nextQueue=[]
            for point in queue:     #这里再遍历每一层
                res.append(point.val)
                if point.left:
                    nextQueue.append(point.left)
                if point.right:
                    nextQueue.append(point.right)
            outList.append(res)
            queue=nextQueue     #这一步很巧妙,用当前层覆盖上一层
        return outList
 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

Of course, it is no problem to use the queue completely, but the key is to confirm the split point of each layer, so a flag bit can be used to record the position of the split point

    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        queue=[pRoot]
        outList=[]
        while queue:
            res=[]
            i=0
            numberFlag=len(queue)   #这一步记录当前层中节点的个数
            while i <numberFlag:    #这里再遍历每一层
                point=queue.pop(0)
                res.append(point.val)
                if point.left:
                    queue.append(point.left)
                if point.right:
                    queue.append(point.right)
                i+=1
            outList.append(res)
        return outList
 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
      <link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-258a4616f7.css" rel="stylesheet">
              </div>
      版权声明:本文为博主原创文章,未经博主允许不得转载。          https://blog.csdn.net/songyunli1111/article/details/81706801        </div>
        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-cd6c485e8b.css">
                          <div id="content_views" class="markdown_views">
        <!-- flowchart 箭头图标 勿删 -->
        <svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
          <path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>
        </svg>
        <h4 id="二叉树的层次遍历">二叉树的层次遍历</h4>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324358566&siteId=291194637