513. 找树左下角的值

原题链接:

513. 找树左下角的值.

https://leetcode.cn/problems/find-bottom-left-tree-value/description/

完成情况:

在这里插入图片描述

解题思路:

_513找树左下角的值_dfs记录高度

package leetcode板块;

public class _513找树左下角的值_dfs记录高度 {
    private 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;
        }
    }

    private int value = 0;
    private int height = 0;
    /**
     *
     * @param root
     * @return
     */
    public int findBottomLeftValue(TreeNode root) {
        //  TODO 找一棵树最下层,并且最左边的值
        //全局化变量,避免函数调用中引入太多的参数
        dfs_findBottomLeftValue(root,0);
        return value;
    }

    /**
     *
     * @param root
     * @param curHeight
     */
    private void dfs_findBottomLeftValue(TreeNode root, int curHeight) {
        if (root == null){
            return;
        }
        curHeight++;
        dfs_findBottomLeftValue(root.left,curHeight);
        dfs_findBottomLeftValue(root.right,curHeight);
        if (curHeight > height){    //说明当前左值,满足我需要找的条件
            height = curHeight;
            value = root.val;
        }
    }
}

_513找树左下角的值_bfs层次最左

package leetcode板块;

import java.util.ArrayDeque;
import java.util.Queue;

public class _513找树左下角的值_bfs层次最左 {
    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;
        }
    }

    /**
     *
     * @param root
     * @return
     */
    public int findBottomLeftValue(TreeNode root){
        int result = 0;
        Queue<TreeNode> myQueue = new ArrayDeque<TreeNode>();
        myQueue.offer(root);
        while (!myQueue.isEmpty()){
            TreeNode curNode = myQueue.poll();
            // 我先存储右边,再存储左边,那么最后一个返回出来的必然就是整颗树的最左边元素
            if (curNode.right != null){
                myQueue.offer(curNode.right);
            }
            if (curNode.left != null){
                myQueue.offer(curNode.left);
            }
            result = curNode.val;
        }
        return result;
    }
}

参考代码:

_513找树左下角的值_dfs记录高度

Sure, let me explain the code provided in detail.

Overview

The code defines a class to solve the problem of finding the bottom-left value in a binary tree using depth-first search (DFS). The code includes an inner class TreeNode representing a node in the tree and the main logic to find the bottom-left value.

Class Definitions

  1. TreeNode Class:
    • Represents a node in a binary tree.
    • Contains three fields: val (the value of the node), left (reference to the left child), and right (reference to the right child).
    • Includes three constructors:
      • Default constructor initializing an empty node.
      • Constructor initializing a node with a given value.
      • Constructor initializing a node with a given value, left child, and right child.

Main Logic

  1. _513找树左下角的值_dfs记录高度 Class:
    • Contains the main logic to find the bottom-left value in the tree.
    • Uses two instance variables:
      • value to store the value of the bottom-left node.
      • height to store the maximum height reached during the DFS traversal.
    • The findBottomLeftValue method:
      • Takes the root of the tree as input.
      • Calls the helper method dfs_findBottomLeftValue to perform DFS traversal.
      • Returns the value of the bottom-left node.
    • The dfs_findBottomLeftValue method:
      • Takes a node (root) and the current height (curHeight) as input.
      • Performs DFS traversal, incrementing curHeight at each level.
      • Checks if the current node is deeper than any previously visited nodes (curHeight > height). If so, updates height and value.

Explanation of dfs_findBottomLeftValue Method

  • Base Case: If the current node (root) is null, return immediately. This prevents further traversal down a non-existent path.
  • Recursive Case:
    • Increment curHeight to reflect moving down one level in the tree.
    • First, recursively call the method on the left child (root.left). This ensures that left-most nodes are visited first.
    • Then, recursively call the method on the right child (root.right).
    • After the recursive calls, check if the current node’s height (curHeight) is greater than the maximum height encountered so far (height). If true, update height and set value to the current node’s value (root.val).

Corrected Implementation

However, there is a logical error in your current implementation: the if (curHeight > height) condition should be checked before the recursive calls to ensure that the left-most node is correctly identified.

Here’s the corrected implementation:

package leetcode板块;

public class _513找树左下角的值_dfs记录高度 {
    private 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;
        }
    }

    private int value = 0;
    private int height = 0;

    public int findBottomLeftValue(TreeNode root) {
        dfs_findBottomLeftValue(root, 0);
        return value;
    }

    private void dfs_findBottomLeftValue(TreeNode root, int curHeight) {
        if (root == null) {
            return;
        }
        curHeight++;
        if (curHeight > height) {    // Check height before recursive calls
            height = curHeight;
            value = root.val;
        }
        dfs_findBottomLeftValue(root.left, curHeight);
        dfs_findBottomLeftValue(root.right, curHeight);
    }
}

Summary

  • The dfs_findBottomLeftValue method performs a DFS traversal to find the left-most node at the maximum depth.
  • The height is checked and updated before making recursive calls to ensure that the left-most node at each level is correctly identified.

_513找树左下角的值_bfs层次最左

Sure, let’s go through the BFS implementation for finding the bottom-left value of a binary tree step by step.

Overview

The code defines a class to solve the problem of finding the bottom-left value in a binary tree using breadth-first search (BFS). This approach uses a queue to traverse the tree level by level from right to left. The last node encountered during this traversal will be the bottom-left node.

Class Definitions

  1. TreeNode Class:
    • Represents a node in a binary tree.
    • Contains three fields: val (the value of the node), left (reference to the left child), and right (reference to the right child).
    • Includes three constructors:
      • Default constructor initializing an empty node.
      • Constructor initializing a node with a given value.
      • Constructor initializing a node with a given value, left child, and right child.

Main Logic

  1. _513找树左下角的值_bfs层次最左 Class:
    • Contains the main logic to find the bottom-left value in the tree.
    • The findBottomLeftValue method:
      • Takes the root of the tree as input.
      • Uses a queue (myQueue) to perform BFS traversal.
      • Returns the value of the bottom-left node.

Explanation of findBottomLeftValue Method

  • Initialization:
    • Initialize result to store the bottom-left value.
    • Create a queue (myQueue) and add the root node to it.
  • BFS Traversal:
    • While the queue is not empty:
      • Poll the current node (curNode) from the front of the queue.
      • Add the right child (curNode.right) to the queue if it exists.
      • Add the left child (curNode.left) to the queue if it exists.
      • Update result with the current node’s value (curNode.val).
  • Return:
    • After the loop, result will hold the value of the bottom-left node.

Key Points

  • By adding the right child before the left child, the BFS ensures that the last node encountered in the traversal will be the left-most node at the deepest level of the tree.

Complete Code

Here is the complete code with detailed comments:

package leetcode板块;

import java.util.ArrayDeque;
import java.util.Queue;

public class _513找树左下角的值_bfs层次最左 {
    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;
        }
    }

    /**
     * Finds the bottom-left value of a binary tree using BFS.
     * @param root The root of the binary tree.
     * @return The value of the bottom-left node.
     */
    public int findBottomLeftValue(TreeNode root) {
        int result = 0;
        Queue<TreeNode> myQueue = new ArrayDeque<TreeNode>();
        myQueue.offer(root);
        while (!myQueue.isEmpty()) {
            TreeNode curNode = myQueue.poll();
            // Add right child first, then left child
            if (curNode.right != null) {
                myQueue.offer(curNode.right);
            }
            if (curNode.left != null) {
                myQueue.offer(curNode.left);
            }
            // Update result with the current node's value
            result = curNode.val;
        }
        return result;
    }
}

Summary

  • The BFS approach traverses the tree level by level from right to left.
  • By adding the right child before the left child to the queue, the last node processed is the left-most node at the deepest level.
  • The result variable stores the value of the bottom-left node, which is returned at the end of the traversal.

错误经验吸取

  • 25
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值