513. Find Bottom Left Tree Value

题目连接

这道题让我们求树的最底层的最左边的元素。

解答:

       像这种求树的一层中的某个元素的题一般用bps。我们用val记录每一层的第一个元素,用bps遍历到最后,val就是最后一层的第一个元素。

      

  public int findBottomLeftValue(TreeNode root) {
        LinkedList<TreeNode> q = new LinkedList<>();
        int val = 0;
        q.offer(root);
        while (!q.isEmpty()) {
            val = q.peekFirst().val;
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = q.poll();
                if (cur.left != null) {
                    q.offer(cur.left);
                }
                if (cur.right != null) {
                    q.offer(cur.right);
                }
            }
        }
        return val;
    }

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac x16r2 xr" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" xmlns:x16r2="http://schemas.microsoft.com/office/spreadsheetml/2015/02/main" xmlns:xr="http://schemas.microsoft.com/office/spreadsheetml/2014/revision"> <fonts count="2" x14ac:knownFonts="1"> <font> <sz val="11"/> <name val="宋体"/> <family val="3"/> <charset val="134"/> </font> <font> <sz val="9"/> <name val="宋体"/> <family val="3"/> <charset val="134"/> </font> </fonts> <fills count="3"> <fill> <patternFill patternType="none"/> </fill> <fill> <patternFill patternType="gray125"/> </fill> <fill> <patternFill patternType="solid"> <fgColor theme="9"/> <bgColor indexed="64"/> </patternFill> </fill> </fills> <borders count="1"> <border> <left/> <right/> <top/> <bottom/> <diagonal/> </border> </borders> <cellStyleXfs count="1"> <xf numFmtId="0" fontId="0" fillId="0" borderId="0"> <alignment vertical="center"/> </xf> </cellStyleXfs> <cellXfs count="2"> <xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"> <alignment vertical="center"/> </xf> <xf numFmtId="0" fontId="0" fillId="2" borderId="0" xfId="0" applyFill="1"> <alignment vertical="center"/> </xf> </cellXfs> <cellStyles count="1"> <cellStyle name="常规" xfId="0" builtinId="0" customBuiltin="1"/> </cellStyles> <dxfs count="0"/> <tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleLight16"/> <extLst> <ext uri="{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"> <x14:slicerStyles defaultSlicerStyle="SlicerStyleLight1"/> </ext> <ext uri="{9260A510-F301-46a8-8635-F512D64BE5F5}" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"> <x15:timelineStyles defaultTimelineStyle="TimeSlicerStyleLight1"/> </ext> </extLst> </styleSheet>
最新发布
05-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值