代码随想录算法训练营Day17 | 二叉树(4/9) LeetCode 110.平衡二叉树 257. 二叉树的所有路径 404.左叶子之和

第一题

110. Balanced Binary Tree

Given a binary tree, determine if it is height-balanced

height-balanced的定义为:一棵二叉树中,左右两个子树的高度差不超过1。

既然要比较高度,必然需要后序遍历

class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return True

        height_map = {}
        stack = [root]
        while stack:
            node = stack.pop()
            if node:
                stack.append(node)
                stack.append(None)
                if node.left: stack.append(node.left)
                if node.right: stack.append(node.right)
            else:
                real_node = stack.pop()
                left, right = height_map.get(real_node.left, 0), height_map.get(real_node.right, 0)
                if abs(left - right) > 1:
                    return False
                height_map[real_node] = 1 + max(left, right)
        return True

第二题

257. Binary Tree Paths

Given the root of a binary tree, return all root-to-leaf paths in any order.

leaf is a node with no children.

这道题涉及到回溯,因为我们要把路径记录下来,需要回溯来回退一个路径再进入另一个路径。

还要结合递归,递归和回溯本是一家人

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

第三题

404. Sum of Left Leaves

Given the root of a binary tree, return the sum of all left leaves.

leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

用递归的方法,后序遍历

class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        if root.left is None and root.right is None:
            return 0
        
        leftValue = self.sumOfLeftLeaves(root.left)  
        if root.left and not root.left.left and not root.left.right: 
            leftValue = root.left.val
            
        rightValue = self.sumOfLeftLeaves(root.right)  

        sum_val = leftValue + rightValue  
        return sum_val

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值