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:

515. Find Largest Value in Each Tree Row_第1张图片
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 largestValues(TreeNode root) {
        List largestValues = new ArrayList<>();
        if (root == null) {
            return largestValues;
        }
        
        Queue 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 largestValues(TreeNode root) {
        List largestValues = new ArrayList<>();
        helper(root, 0, largestValues);
        return largestValues;
    }
    
    private void helper(TreeNode root, int depth, List 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);        
    }
}

你可能感兴趣的:(515. Find Largest Value in Each Tree Row)