LeetCode刷题(三)

102. Binary Tree Level Order Traversal

Description

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

Example

Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
     / \
   15   7

return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]

思路及代码

这里题目的要求为层次遍历二叉树并且每一层为一行,输出二维数组。我们用二叉树的层次遍历方法,然后再设置一个列表用于存储每一层的元素的值,用递归的方法,将未遍历的子树存入列表中,若列表不为空,则说明还有下一层节点,继续遍历,每遍历完一层就将该层的元素的值存入res列表中,然后将res列表添加到输出列表中。对应的Python代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        outList=[]
        queue = [root]
        while queue:
            nextQueue = []
            res = []
            for point in queue:
                res.append(point.val)
                if point.left:
                    nextQueue.append(point.left)
                if point.right:
                    nextQueue.append(point.right)
                
            queue = nextQueue
            outList.append(res)
        return outList

运行时间24ms,占用内存12.1MB。
当然上面的用于存储树的信息的列表也可以用队列来存储,不过Python中的队列也是用列表来实现的,效果也不见得比用列表好,用队列的代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        outList=[]
        queue = [root]
        while queue:
            res = []
            i = 0
            nextQueue = []
            while i < len(queue):
                point = queue.pop(0)
                res.append(point.val)
                if point.left:
                    nextQueue.append(point.left)
                if point.right:
                    nextQueue.append(point.right)
            i += 1
            outList.append(res)
            queue = nextQueue
        return outList

因为用队列存储节点信息,所以我们需要用一个标记i来记录遍历的位置,上面的代码的运行时间为36ms,占用内存12.3MB。

94. Binary Tree Inorder Traversal

Description

Given a binary tree, return the inorder traversal of its nodes’ values.

Example 1

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

Follow up

Recursive solution is trivial, could you do it iteratively?

思路及代码

根据上面的例子,可以看出题目要求我们中序遍历二叉树并且返回中序遍历后的元素列表。这里先用递归的方法遍历二叉树,对应的Python代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        # 递归中序遍历
        resList = [] 
        if root:
            resList += self.inorderTraversal(root.left)
            resList.append(root.val)
            resList += self.inorderTraversal(root.right)
        return resList
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值