8.5笔记

513. 找树左下角的值(其实就是按层遍历二叉树)

class Solution(object):
    def findBottomLeftValue(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return
        stack = [root]
        while stack:
            stack1 = []
            x = stack[0].val
            while stack:
                a = stack.pop(0)
                if a.left:
                    stack1.append(a.left)
                if a.right:
                    stack1.append(a.right)
            stack = stack1
        return x

515. 在每个树行中找最大值(非递归版本)

class Solution(object):
    def largestValues(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return 
        res = []
        stack = [root]
        while stack:
            stack1 = []
            max1 = stack[0].val
            while stack:
                a = stack.pop(0)
                max1 = max(max1,a.val)
                if a.left:
                    stack1.append(a.left)
                if a.right:
                    stack1.append(a.right)
            res.append(max1)
            stack = stack1
        return res
            

递归版本:

class Solution(object):
    def largestValues(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
    #递归
        res = []
        self.getval(res,root,0)
        return res
    def getval(self,res,root,deep):
        if not root:
            return
        if len(res) == deep:
            res.append(root.val)
        elif res[deep]< root.val:
            res[deep] = root.val
        self.getval(res,root.left,deep+1)
        self.getval(res,root.right,deep+1)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值