513. Find Bottom Left Tree Value

给定一棵二叉树,找到最后一层最左边的节点的值。方法包括直接层序遍历和利用队列实现从右到左的层序遍历。

题目描述

Given a binary tree, find the leftmost value in the last row of the tree.
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

方法思路

Appraoch1:
简单粗暴的方法

class Solution {
    //Runtime: 3 ms, faster than 95.43%
    //Memory Usage: 39.8 MB, less than 11.18%
    int depth, ans;
    public int findBottomLeftValue(TreeNode root) {
        depth = 0; 
        ans = root.val;
        if(root.left == null && root.right == null)
            return ans;
        find_Helper(root, 0);
        return ans; 
    }
    public void find_Helper(TreeNode root, int sub_depth){
        if(root == null) return;
        if(root.left != null && root.left.left == null && root.left.right == null){
            if((sub_depth + 1) > depth){
                depth = sub_depth + 1;
                ans = root.left.val;
            }
        }
        if(root.right != null && root.right.left == null && root.right.right == null){
            if((sub_depth + 1) > depth){
                depth = sub_depth;
                ans = root.right.val;
            }
        }
        find_Helper(root.left, sub_depth + 1);
        find_Helper(root.right, sub_depth + 1);
    }
}

Appraoch2:
利用队列的数据结构,进行从右至左的层序遍历

class Solution {
    //Runtime: 4 ms, faster than 64.10%
    //Memory Usage: 40.2 MB, less than 5.30%
    public int findBottomLeftValue(TreeNode root) {
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);
    while (!queue.isEmpty()) {
        root = queue.poll();
        if (root.right != null)
            queue.add(root.right);
        if (root.left != null)
            queue.add(root.left);
    }
    return root.val;
}
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值