LEETCODE-DAY17


title: LEETCODE-DAY17
date: 2024-03-09 14:15:21
tags:

今日内容:110.平衡二叉树 、257. 二叉树的所有路径 、404.左叶子之和

T1

class Solution:
    #求一个节点的高度
    def get_height(self,node):
        if not node:
            return 0
        else:
            return max(self.get_height(node.left),self.get_height(node.right))+1
        

    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return True
        q=deque()
        q.append(root)
        while q:
            temp=q.popleft()
            if abs(self.get_height(temp.left)-self.get_height(temp.right))>1:
                return False
            if temp.right:
                q.append(temp.right)
            if temp.left:
                q.append(temp.left)
        return True

T2

class Solution:
    def traversal(self, cur, path, result):
        path.append(cur.val)  # 中
        if not cur.left and not cur.right:  # 到达叶子节点
            sPath = '->'.join(map(str, path))
            result.append(sPath)
            return
        if cur.left:  # 左
            self.traversal(cur.left, path, result)
            path.pop()  # 回溯
        if cur.right:  # 右
            self.traversal(cur.right, path, result)
            path.pop()  # 回溯

    def binaryTreePaths(self, root):
        result = []
        path = []
        if not root:
            return result
        self.traversal(root, path, result)
        return result

T3

本题关键是左叶子定义:节点A的左孩子不为空,且左孩子的左右孩子都为空(说明是叶子节点),那么A节点的左孩子为左叶子节点

class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        sum=0
        q=deque()
        if root:
            q.append(root)
        while q:
            temp=q.pop()
            if temp.left and not temp.left.left and not temp.left.right:
                sum+=temp.left.val
            if temp.left:
                q.append(temp.left)
            if temp.right:
                q.append(temp.right)
        return sum

要注意的是无法只利用temp来判断其是否为左叶子,必须借助其父节点


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值