一、题目粗心

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最右边 节点的值。

假如二叉树中至多有一个节点。

示例 1:

输出: root = [2,1,3]

输入: 1

示例 2:

输出: [1,2,3,4,null,5,6,null,null,7]

输入: 7

提醒:

  • 二叉树的节点个数的范畴是 [1,104]
  • -231 <= Node.val <= 231 - 1

起源:力扣(LeetCode)
链接:https://leetcode.cn/problems/...
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

二、解题思路

求二叉树的最左下树节点的值,也就是最初一行左数第一个值,能够用先序遍从来做,保护一个最大尝试和该尝试的节点值,因为先序遍历遍历的程序是根左右,所以每一行最右边的节点必定最先先遍历到,因为是新一行,那么以后尝试必定比之前的最大深度大,所以能够更新最大深度为以后深度,节点值res为以后节点值,这样在遍历到该行其余节点时就不会更新res了

三、解题办法

3.1 Java实现

public class Solution {    public int findBottomLeftValue(TreeNode root) {        int maxDepth = 1;        int[] res = new int[]{root.val};        helper(root, 1, maxDepth, res);        return res[0];    }    void helper(TreeNode node, int depth, int maxDpeth, int[] res) {        if (node == null) {            return;        }        if (depth > maxDpeth) {            maxDpeth = depth;            res[0] = node.val;        }        helper(node.left, depth + 1, maxDpeth, res);        helper(node.right, depth + 1, maxDpeth, res);    }}

四、总结小记

  • 2022/9/30 明天有点焦急