Leetcode110, 257, 404

Leetcode110

题目:判断平衡二叉树

学习资料:代码随想录

实现过程

  • 判断左子树和右子树高度差不大于一
  • 求高度可以利用后序遍历
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        def check(root):
            if root == None:
                return 0


            leftD = check(root.left)
            if leftD == -1: return -1

            rightD = check(root.right)
            if rightD == -1: return -1

            re = 0
            if abs(leftD - rightD) >1 :
                re = -1
            else:
                re = 1 + max(leftD, rightD)
            return re
          
        if check(root) != -1:
            return True
        else:
            return False

Leetcode257

题目:二叉树的所有路径

学习资料: 代码随想录

实现过程

  • 回溯的方法
  • 注意要先将结点添加到path中,再判断,不然会漏掉叶子结点
  • 这里的回溯使用字符串path,只做内容拷贝,那么回溯之后path还是原来的path,不同于list需要pop出来
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        path = ""
        re = []
        if not root:return root
        self.backtracking(root, path, re)
        return re


    def backtracking(self, root, path, re):
        # 中结点,叶子结点要包含上
        path += str(root.val)
        if not root.left and not root.right :
            re.append(path[:])

        if root.left:
            # path 是字符串类型,path只做内容拷贝
            self.backtracking(root.left, path + '->', re)

        if root.right:
            self.backtracking(root.right, path + '->', re)

Leetcode404

题目:左叶子之和

学习资料: 代码随想录

 实现过程

  • 关键如何判断是否为左叶子,需要利用父节点来判断,就是该结点的左孩子不为空,其该结点左孩子的左右孩子都为空
  • 利用后序遍历来返回,左子树左叶子的个数和右子树左叶子的个数,然后中间结点来相加
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        return self.findLeftLeaves(root)
    def findLeftLeaves(self, root):
        if root == None:
            return 0

        leftLeaves = self.findLeftLeaves(root.left)

        if root.left != None and root.left.left == None and root.left.right == None:
            leftLeaves = root.left.val

        rightLeaves = self.findLeftLeaves(root.right)

        nums = leftLeaves + rightLeaves

        return nums

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值