[解题笔记] LeetCode 7月挑战题目之2

    技术2024-08-18  68

    Binary Tree Level Order Traversal II

    这是我第一次参加 LeetCode (力扣) 的每月挑战题组,希望留下点笔记,大家可以参考和互相讨论。😃

    第二天问:

    已给一棵二叉树 (binary tree), 请返回从底部层序遍历 (由下到上,由左到右) 所有节点的数字。

    题目要求 (引用自LeetCode):假设有以下一棵树:

    input = [3,9,20,null,null,15,7] Tree diagram: 3 / \ 9 20 / \ 15 7

    经过你的程序运算,应该可以得到以下列表: [ [15,7], [9,20], [3] ]

    解题思路:

    这条问题,对现在的我来说其实挺难的,因为这涉及解题者对二叉树结杓的了解,而我只是刚学了数据结构沒多少天🤦‍♂️。查了很多有关二叉树的结构应用之后,终於都让我想到方法。

    其实所谓从底层遍历,到最后还是要从頂部开始,大概思路是:

    先分析第一层根节点,把它的数据先记录好用迭代找出现时所有节点的所有左、右子节点再把找出来的子节点替换现在分析的节点重复以上动作,直到完全沒有节点需要分析把頂部遍历的结果反过来,便是底层遍历的结果

    代码 (时间复杂度:O(n), n = total number of nodes)

    # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: result = [] #用来装返回结果用的列表 if root is None: #沒有数据,返回空列表 return result current = [root] #把根节点列为现时遍历的节点 while len(current) != 0: #若现时节点不是空白 (所以长度为0) result.append([i.val for i in current]) current_new = [] for i in current: #把现时遍历节点的左右节点放进新列表 if i.left is not None: current_new.append(i.left) if i.right is not None: current_new.append(i.right) current = current_new #把新列表设为现时节点列表 return reversed(result) #把答案列表反过来便是
    Processed: 0.025, SQL: 9