Leetcode 513. 找树左下角的值

本题可以使用深搜或者广搜来解决. 对于一个思想或者方法, 一定要思考得深入一点, 如果下次知道这个解法, 但是没有写出来, 那么就说明是因为没有深入思考.

BFS 

广搜和二叉树的结合, 一个典型的例子就是层次打印二叉树. 一般来说, 使用一个队列来完成遍历, 这里要求的是最左边的值. 因为先入队的先出队, 所以在加入队列的时候, 先加入其右节点, 再加入其左节点. 这样最后出队的肯定是最低层, 最左边的节点.

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        if (root == null) return 0;
        return dfs(root);
    }
    public int dfs(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        TreeNode temp = null;
        while(queue.size() > 0) {
            temp = queue.poll();
            if (temp.right != null) queue.add(temp.right);
            if (temp.left != null) queue.add(temp.left);
        }
        return temp.val;
    }
}

DFS

用一个长度为 2 的数组存储结果, result[0] 表示对应的节点的值, result[1] 表示对应的深度.

class Solution {
    // result[0] 表示节点的值 result[1] 表示节点的深度
    int[] result = new int[]{0, -1}; 
    public int findBottomLeftValue(TreeNode root) {
        dfs(root, 0);
        return result[0];
    }
    public void dfs(TreeNode root, int depth) {
        if (root == null)   return;
        if (depth > result[1]) {
            result[0] = root.val;
            result[1] = depth;
        }
        dfs(root.left, depth + 1);
        dfs(root.right, depth + 1);
    }
}

后面还会有 DFS 和 BFS 的相关题目.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值