Leetcode 515 Find Largest Value in Each Tree Row

xiaoxiao2021-02-28  122

You need to find the largest value in each row of a binary tree.

Example:

Input: 1 / \ 3 2 / \ \ 5 3 9 Output: [1, 3, 9]

DFS的问题,采用pre-order,depth来记录深度

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> largestValues(TreeNode root) { List<Integer> result = new ArrayList<>(); dfs(root, result, 0); return result; } private void dfs(TreeNode root, List<Integer> result, int depth){ if(root == null){ return; } if(result.size() == depth){ result.add(root.val); }else{ result.set(depth, Math.max(result.get(depth), root.val)); } dfs(root.left, result, depth + 1); dfs(root.right, result, depth + 1); } }

转载请注明原文地址: https://www.6miu.com/read-35655.html

最新回复(0)