數組生成二叉樹python代碼-層序遍歷-適用於測試用例的生成

class Solution(object):
    def genTree(self, arr):
        def gen(arr, i):
            if i < len(arr):
                tn = TreeNode(arr[i]) if arr[i] is not None else None
                if tn is not None:
                    tn.left = gen(arr, 2 * i + 1)
                    tn.right = gen(arr, 2 * i + 2)
                return tn
        return gen(arr, 0)

if __name__ == '__main__':
     root = Solution().genTree([3, 1, 5, 0, 2, 4, 6, None, None, None, 3])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章