• 从层序遍历构造一棵二叉树


    在网上找了一下,跑了一下代码,发现竟然是错的。无奈,还是自己写吧。

    核心代码:

    def buildTree(data: List[int]):
        count = 0
        q = Queue()
        root = TreeNode(data[0])
        q.put(root)
        curNode = None
    
        for i in range(1, len(data)):
            node = TreeNode(data[i]) if data[i] != None else None
            if count == 0:
                curNode = q.get()
                count += 1
                curNode.left = node
            else:
                count = 0
                curNode.right = node
            if data[i] != None:
                q.put(node)
        
        return root
    

    完整代码:

    from queue import Queue
    from typing import List
    
    
    class TreeNode:
        def __init__(self, val):
            self.val = val
            self.right = None
            self.left = None
    
        def insert(self, val):
            if self.val == val:
                return
            elif self.val < val:
                if self.right is None:
                    self.right = TreeNode(val)
                else:
                    self.right.insert(val)
            else:  # self.val > val
                if self.left is None:
                    self.left = TreeNode(val)
                else:
                    self.left.insert(val)
    
        def display(self):
            lines, *_ = self._display_aux()
            for line in lines:
                print(line)
    
        def _display_aux(self):
            """Returns list of strings, width, height, and horizontal coordinate of the root."""
            # No child.
            if self.right is None and self.left is None:
                line = '%s' % self.val
                width = len(line)
                height = 1
                middle = width // 2
                return [line], width, height, middle
    
            # Only left child.
            if self.right is None:
                lines, n, p, x = self.left._display_aux()
                s = '%s' % self.val
                u = len(s)
                first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s
                second_line = x * ' ' + '/' + (n - x - 1 + u) * ' '
                shifted_lines = [line + u * ' ' for line in lines]
                return [first_line, second_line] + shifted_lines, n + u, p + 2, n + u // 2
    
            # Only right child.
            if self.left is None:
                lines, n, p, x = self.right._display_aux()
                s = '%s' % self.val
                u = len(s)
                first_line = s + x * '_' + (n - x) * ' '
                second_line = (u + x) * ' ' + '\\' + (n - x - 1) * ' '
                shifted_lines = [u * ' ' + line for line in lines]
                return [first_line, second_line] + shifted_lines, n + u, p + 2, u // 2
    
            # Two children.
            left, n, p, x = self.left._display_aux()
            right, m, q, y = self.right._display_aux()
            s = '%s' % self.val
            u = len(s)
            first_line = (x + 1) * ' ' + (n - x - 1) * \
                '_' + s + y * '_' + (m - y) * ' '
            second_line = x * ' ' + '/' + \
                (n - x - 1 + u + y) * ' ' + '\\' + (m - y - 1) * ' '
            if p < q:
                left += [n * ' '] * (q - p)
            elif q < p:
                right += [m * ' '] * (p - q)
            zipped_lines = zip(left, right)
            lines = [first_line, second_line] + \
                [a + u * ' ' + b for a, b in zipped_lines]
            return lines, n + m + u, max(p, q) + 2, n + u // 2
    
    def buildTree(data: List[int]):
        count = 0
        q = Queue()
        root = TreeNode(data[0])
        q.put(root)
        curNode = None
    
        for i in range(1, len(data)):
            node = TreeNode(data[i]) if data[i] != None else None
            if count == 0:
                curNode = q.get()
                count += 1
                curNode.left = node
            else:
                count = 0
                curNode.right = node
            if data[i] != None:
                q.put(node)
        
        return root
    
    data = [4, -7, -3, None, None, -9, -3, 9, -7, -4, None, 6, None, -6, -6, None, None, 0, 6, 5, None, 9, None, None, -1, -4, None, None, None, -2]
    root = buildTree(data)
    root.display()
    
    

    运行结果:

      4_____________________
     /                      \
    -7           __________-3___
                /               \
               -9____          -3
              /      \        /
           ___9     -7____   -4
          /        /      \
        __6__     -6     -6
       /     \   /      /
       0_    6   5      9
         \  /          /
        -1 -4         -2
    
  • 相关阅读:
    Android 自动化测试 Emmagee
    接口测试
    office2010
    MonkeyRecorder
    反编译android的apk
    基于标准库的string类实现简单的字符串替换
    C++中如何在顺序容器中删除符合特定条件的元素
    结合示例说明C++中const和指针结合时怎么理解
    C++中const使用注意要点(二)
    C++中const使用注意要点(一)
  • 原文地址:https://www.cnblogs.com/fanlumaster/p/16047907.html
Copyright © 2020-2023  润新知