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


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

    核心代码:

    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
    
  • 相关阅读:
    fastjson的@JSONField注解
    Java 日期比较大小
    linux 查看文件显示行号
    Java double 加、减、乘、除
    Java 身份证判断性别获取年龄
    linux 查看端口被占用
    Unable to complete the scan for annotations for web application [/wrs] due to a StackOverflowError. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies.
    nginx 返回数据不完整
    linux redis 启动 overcommit_memory
    IntelliJ IDEA 常用设置
  • 原文地址:https://www.cnblogs.com/fanlumaster/p/16047907.html
Copyright © 2020-2023  润新知