找树左下角的值

BFS
用队列存储节点,先进先出
从右往左遍历,也就是在往队列中添加数据时,先添加右子节点,再添加左子节点
当队列为空时,循环结束,最后一个遍历到的节点就是最左边的节点
返回最左边节点的值

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        TreeNode node = null;
        while(!queue.isEmpty()){
            node = queue.poll();
            // 先右后左
            if(node.right != null){
                queue.offer(node.right);
            }
            if(node.left != null){
                queue.offer(node.left);
            }
        }
        return node.val;
    }
}

DFS
只有叶子节点可能是需要的返回值res,所以递归的中止条件为当遇到叶子节点才return
只有当前叶子节点的深度比之前的更大,才更新res
PS:因为要大于才会更新,所以每一层只会更新一次,先会遍历到左边的节点,所以只会更新每层最左侧的节点,符合题目要求
因为要比较深度,在递归中除了节点作为参数外,还需要增加深度参数
在res中增加一项专门用于存储深度, 即 res = [叶子节点值,叶子节点深度]
最后返回的是res[0]

class Solution {
    private int[] res;
    public int findBottomLeftValue(TreeNode root) {
        res = new int[]{0, -1};
        dfs(root, 0);
        return res[0];
    }

    private void dfs(TreeNode node, int level){
        if(node.left == null && node.right == null){
            if(level > res[1]){
                res[0] = node.val;
                res[1] = level;
            }
            return;
        }
        if(node.left != null){
            dfs(node.left, level + 1);
        }
        if(node.right != null){
            dfs(node.right, level + 1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值