LCR 045. 找树左下角的值(中等)(主站513)

https://leetcode.cn/problems/LwUNpT/
https://leetcode.cn/problems/find-bottom-left-tree-value/
难度:☆☆☆

题目:

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。假设二叉树中至少有一个节点。

示例:

在这里插入图片描述
输入: root = [2,1,3]
输出: 1

方法1:深度优先搜索BFS

Python

class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        curval, curheight = 0, 0
        
        def dfs(node, height):
            nonlocal curval, curheight
            if not node:
                return
            height += 1
            dfs(node.left, height)
            dfs(node.right, height)
            if height > curheight:
                curheight = height
                curval = node.val
        
        dfs(root, 0)
        return curval

Java

class Solution {
    int curVal = 0;
    int curHeight = 0;
    
    public int findBottomLeftValue(TreeNode root) {
        dfs(root, 0);
        return curVal;
    }

    public void dfs(TreeNode node, int height) {
        if (node == null) {
            return;
        }
        height++;
        dfs(node.left, height);
        dfs(node.right, height);
        if (height > curHeight) {
            curHeight = height;
            curVal = node.val;
        }
    }
}

方法2:广度优先搜索DFS

使用广度优先搜索遍历每一层的节点。
在遍历一个节点时,需要先把它的非空右子节点放入队列,然后再把它的非空左子节点放入队列,
这样才能保证广度优先搜索所遍历的最后一个节点的值就是最底层最左边节点的值。
Python

class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        from collections import deque
        ans = 0
        q = deque([root])

        while q:
            node = q.popleft()
            if node.right:
                q.append(node.right)
            if node.left:
                q.append(node.left)
            ans = node.val
        return ans

Java

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue = new ArrayDeque<>();
        int ans = 0;
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node.right != null) {
                queue.offer(node.right);
            }
            if (node.left != null) {
                queue.offer(node.left);
            }
            ans = node.val;
        }
        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值