代码随想录算法训练营第十四天 | leetcode 层序遍历、226翻转二叉树、101对称二叉树)

代码随想录算法训练营第十四天 | leetcode 层序遍历、226翻转二叉树、101对称二叉树

层序遍历

题目链接:102-二叉树的层序遍历

# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        results = []
        if not root:
            return results

        from collections import deque
        que = deque([root])

        while que:
            size = len(que)
            result = []
            for _ in range(size):
             #移除列表中的一个元素(默认最左端的一个元素),并且返回该元素的值
                cur = que.popleft()
                result.append(cur.val)
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)
            results.append(result)
        return results

题目链接:107-二叉树的层序遍历 II

与刚才不同的是题目要求为:自底向上的层序遍历

results.reverse()
#在上题的代码中,return 上方加一句话就好了

题目链接:199. 二叉树的右视图

题目要求:返回从右往左看见的第一个结点

# 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 rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        results = []
        if not root:
            return results
        
        from collections import deque
        que = deque([root])
        result = []
        while que:
            node = que[-1] 

            result.append(node.val)
            for _ in range(len(que)):
                node = que.popleft()
                
                if node.left:
                    que.append(node.left)
                if node.right:
                    que.append(node.right)
        return result

题目链接:637-二叉树的层平均值
思路:与第一题思路类似,就是要把弹出的数字记录下来

class Solution:
    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
        results = []
        if not root:
            return results
        
        from collections import deque
        que = deque([root])

        while que:
            size = len(que)
            sum_ = 0
            for _ in range(size):
                cur = que.popleft()
                sum_ += cur.val
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)
            results.append(sum_ / size)

        return results

题目链接:429-N 叉树的层序遍历

class Solution:
    def levelOrder(self, root: 'Node') -> List[List[int]]:
        results = []
        if not root:
            return results
        
        from collections import deque
        que = deque([root])

        while que:
            result = [] #append命令是将整个对象加在列表末尾;而extend命令是将新对象中的元素逐一加在列表的末尾
            for _ in range(len(que)):
                cur = que.popleft()
                result.append(cur.val)
                if cur.children:
                    que.extend(cur.children)
            results.append(result)

        return results

题目链接:515-在每个树行中找最大值

class Solution:
    def largestValues(self, root: Optional[TreeNode]) -> List[int]:
        results = []
        if not root:
            return results
        
        from collections import deque
        que = deque([root])
        result = []
        while que: 
            cur = -inf

            for _ in range(len(que)):
                node = que.popleft()
                cur = max(cur, node.val)
                
                if node.left:
                    que.append(node.left)   
                if node.right:
                    que.append(node.right)

            result.append(cur)
        return result
       

题目链接:116-填充每个节点的下一个右侧节点指针

class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if not root:
            return None
        queue = [root]
        while queue:
            n = len(queue)
            for i in range(n):
                node = queue.pop(0)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                if i == n - 1:
                    break
                node.next = queue[0]
        return root

我尝试用双向链表去求,但是队列queue里面似乎装不了元素进去

题目链接:117-填充每个节点的下一个右侧节点指针 II

class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if not root:
            return None

        queue = [root]
        while queue: #遍历每一层
            tail = None #每一层维护一个尾结点
            for i in range(len(queue)):  #遍历当前层
                curnode = queue.pop(0)
                if tail:
                    tail.next = curnode  #尾结点指向当前结点
                tail = curnode #让当前结点成为尾结点
                if curnode.left:
                    queue.append(curnode.left)
                if curnode.right:
                    queue.append(curnode.right)
        return root

题目链接:104-二叉树的最大深度

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        
        from collections import deque
        que = deque([root])

        depth = 0
        while que:
            for i in range(len(que)):
                cur = que.popleft()
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)
            depth += 1
        return depth

题目链接111-二叉树的最小深度

	#最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        
        from collections import deque
        que = deque([root])
        depth = 1
        while que:
            for _ in range(len(que)):
                cur = que.popleft()
                if cur.left == None and cur.right == None:
                    return depth
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)
            depth += 1
        return 0

226-翻转二叉树

题目:翻转一棵二叉树。

题目链接:226-翻转二叉树

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None
        root.left, root.right = root.right, root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

101-对称二叉树

题目:检查一棵二叉树是否轴对称

题目链接:101-对称二叉树

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return True
        return self.compare(root.left, root.right)

    def compare(self, left, right): #确定递归函数的参数和返回值
        if left == None and right != None:  #确定终止条件
            return False
        elif right == None and left != None:
            return False
        elif right == None and left == None:
            return True
        elif left.val != right.val:
            return False
        
        #确定单层递归逻辑
        outside = self.compare(left.left, right.right) # 比较外层
        inside = self.compare(left.right, right.left) # 比较内层
        issame = outside and inside # 两个相同才返回真
        return issame
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值