离散的前序遍历是指使用数组表示二叉树时,按照前序遍历的顺序将节点的值存储在数组中。如果某个节点为空,则用一个特定的值(如-1)表示。

例如,对于如下的二叉树:

     1
   /   \
  2     3
 / \   / \
4   5 6   7

其离散的前序遍历为:1 2 4 -1 -1 5 -1 -1 3 6 -1 -1 7 -1 -1

其中,-1表示空节点。

例题:给定一个离散的前序遍历,重建原二叉树。

输入:1 2 4 -1 -1 5 -1 -1 3 6 -1 -1 7 -1 -1
输出:
     1
   /   \
  2     3
 / \   / \
4   5 6   7

解法:使用递归的方法重建二叉树。对于当前的节点,在数组中读取其值。如果其值为-1,则说明该节点为空;否则,创建一个新的节点,并递归构建其左右子树。

Python代码如下:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def buildTree(self, preorder: List[int]) -> TreeNode:
        def build(i):
            nonlocal index
            if i >= len(preorder) or preorder[i] == -1:
                return None
            root = TreeNode(preorder[i])
            index += 1
            root.left = build(index)
            index += 1
            root.right = build(index)
            return root
        
        index = 0
        return build(0)
离散前序遍历:概念、示例及重建二叉树

原文地址: https://www.cveoy.top/t/topic/oTir 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录