Python 列表如何轉化爲二叉樹?

Day46: 列表轉化爲二叉樹

已知列表nums,將其轉化爲二叉樹。舉例:node

nums = [3,9,20,None,None,15,7],轉化爲二叉樹後:web

節點3的左子節點9,右子節點20,9的左右子節點都爲None,20的左子節點15,右子節點7,參考下面:算法

二叉樹定義:微信

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

請補全下面函數:數據結構

def list_to_binarytree(nums):
    pass

構建分析

構建知足以上結構的二叉樹,能夠觀察到:樹的父節點和左右子節點的關係:編輯器

基於以上公式,再使用遞歸構建二叉樹。svg

遞歸基狀況:函數

if index >= len(nums) or nums[index] is None:
    return None

遞歸方程:flex

根據以上獲得以下代碼:url

代碼

def list_to_binarytree(nums):
    def level(index):
        if index >= len(nums) or nums[index] is None:
            return None
        
        root = TreeNode(nums[index])
        root.left = level(2 * index + 1)
        root.right = level(2 * index + 2)
        return root

    return level(0)

binary_tree = list_to_binarytree([3,9,20,None,None,15,7])

以上遞歸版本,代碼比較簡潔。除此以外,爲了訓練算法思惟,咱們還能夠使用迭代構建二叉樹,使用隊列數據結構。可是代碼相對複雜一點,這個等再過幾天佈置這個做業。

《end》

本文分享自微信公衆號 - Python與算法社區(alg-channel)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索