【LeetCode】515. Find the maximum value in each tree row

topic

Given the root node of a binary tree  root , find the maximum value at each level of the binary tree.

Example 1:

Input: root = [1,3,2,5,3,null,9]
 Output: [1,3,9]

Example 2:

Input: root = [1,2,3]
 Output: [1,3]

hint:

  • The range of the number of nodes in a binary tree is [0,10^4]
  • -2^31 <= Node.val <= 2^31 - 1

answer

source code

/**
 * 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 List<Integer> largestValues(TreeNode root) {
        if (root == null) {
            return new ArrayList<Integer>();
        }

        List<Integer> res = new ArrayList<>();
        dfs(root, res, 0);

        return res;
    }

    public void dfs(TreeNode root, List<Integer> res, int curHeight) {
        if (curHeight == res.size()) {
            res.add(root.val);
        } else {
            res.set(curHeight, Math.max(res.get(curHeight), root.val));
        }

        if (root.left != null) {
            dfs(root.left, res, curHeight + 1);
        }

        if (root.right != null) {
            dfs(root.right, res, curHeight + 1);
        }
    }
}

Summarize

Traverse the binary tree in depth and record the number of layers of the current node, compare it with the value of the corresponding layer in the list, and update the maximum value.

Guess you like

Origin blog.csdn.net/qq_57438473/article/details/132650401