代码随想录训练营Day16

34 阅读1分钟

513.找树左下角的值 leetcode.com/problems/fi…

思路:要走到最下面一行找最左边的节点,遍历一下,找到叶子节点就更新一下最大深度,

class Solution {
     public int MAX_DEPTH = Integer.MIN_VALUE;
    public int result = 0;
    public int findBottomLeftValue(TreeNode root) {
        if (root == null) return 0;
        // depth应该是1开始吧
        traversal(root, 1);
        return result;
    }

    private void traversal(TreeNode root, int depth) {
        
        // 找到叶子节点 更新depth
        if (root.left == null && root.right == null) {
            if (depth > MAX_DEPTH) {
                MAX_DEPTH = depth;
                result = root.val;
            }
        }
        if (root.left != null) {
            depth++;
            traversal(root.left, depth);
            // 遍历结束了 开始回溯
            depth--;
        }

         if (root.right != null) {
            depth++;
            traversal(root.right, depth);
            // 遍历结束了 开始回溯
            depth--;
        }
    }
}
  1. 路径总和 leetcode.com/problems/pa…

TODO