0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Leetcode 515. Find Largest Value in Each Tree Row

Last updated at Posted at 2023-10-24

アプローチ

  • DFS
/**
 * Definition for a binary tree node.
 * 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;
 *     }
 * }
 */
class Solution {
    public HashMap<Integer, Integer> hashMap;

    public List<Integer> largestValues(TreeNode root) {
        hashMap = new HashMap<>();
        dfs(root, Integer.MIN_VALUE, hashMap);
        return hashMap.values().stream().toList();
    }


    public void dfs(TreeNode root, int depth, HashMap<Integer, Integer> hashMap) {

        if (root == null) {
            return;
        }

        int val = hashMap.getOrDefault(depth, Integer.MIN_VALUE);

        if (val <= root.val) {
            hashMap.put(depth, root.val);
        }

        dfs(root.left, depth + 1, hashMap);
        dfs(root.right, depth + 1, hashMap);
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?