力扣513 找树左下角的值

题目:

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

示例:

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

思路:

分析一下题目:在树的最后一行找到最左边的值

(1)如何判断是最后一行:深度最大的叶子节点一定是最后一行。

(2)如何找最左边:可以使用前序遍历(当然中序,后序都可以,因为本题没有 中间节点的处理逻辑,只要左优先就行),保证优先左边搜索。

记录深度最大的叶子节点,此时就是树的最后一行最左边的值。

class Solution {
    private int Deep = 0;//最大深度
    private int value = 0;//最大深度最左节点的数值
    public int findBottomLeftValue(TreeNode root) {
        value = root.val;
        findLeftValue(root,0);
        return value;
    }
     private void findLeftValue (TreeNode root,int deep) {
        if (root == null) return;
        if (root.left == null && root.right == null) {
            if (deep > Deep) {
                value = root.val;//更新最左值
                Deep = deep;//保证最底层
            }
        }
        if (root.left != null) findLeftValue(root.left,deep + 1);
        //depth++; 
        //findLeftValue(root.left, depth); 
        //depth--; // 回溯:返回再找其他路径
        if (root.right != null) findLeftValue(root.right,deep + 1);
    }
}

 

posted @ 2023-02-01 00:19  壹索007  阅读(42)  评论(0)    收藏  举报