515. Find Largest Value in Each Tree Row

Description

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

Example:

Input:

tree

Output: [1, 3, 9]

Solution

BFS, time O(n), space O(n)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> largestValues = new ArrayList<>();
        if (root == null) {
            return largestValues;
        }
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            int max = Integer.MIN_VALUE;
            
            while (size-- > 0) {
                TreeNode curr = queue.poll();
                max = Math.max(max, curr.val);
                
                if (curr.left != null) queue.offer(curr.left);
                if (curr.right != null) queue.offer(curr.right);
            }
            
            largestValues.add(max);
        } 
        
        return largestValues;
    }
}

DFS base on depth, time O(n), space O(h)

Just a simple pre-order traverse idea. Use depth to expand result list size and put the max value in the appropriate position.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> largestValues = new ArrayList<>();
        helper(root, 0, largestValues);
        return largestValues;
    }
    
    private void helper(TreeNode root, int depth, List<Integer> largestValues) {
        if (root == null) {
            return;
        }
        
        if (depth == largestValues.size()) {
            largestValues.add(root.val);
        }
        
        largestValues.set(depth, Math.max(largestValues.get(depth), root.val));
        helper(root.left, depth + 1, largestValues);
        helper(root.right, depth + 1, largestValues);        
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容