515. Find Largest Value in Each Tree Row

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

Solution1:DFS

思路:
Time Complexity: O(N) Space Complexity: O(N)递归缓存

Solution2:BFS

思路:
Time Complexity: O(N) Space Complexity: O(N)

Solution1 Code:

public class Solution {
    public List largestValues(TreeNode root) {
        List result = new ArrayList();
        dfs(root, result, 0);
        return result;
    }
    private void dfs(TreeNode root, List result, int d){
        if(root == null) {
            return;
        }
        // expand list size
        if(d == result.size()){
            result.add(root.val);
        }
        else{
            // or set value
            result.set(d, Math.max(result.get(d), root.val));
        }
        dfs(root.left, result, d + 1);
        dfs(root.right, result, d + 1);
    }
}

Solution2 Code:

class Solution {
    public List largestValues(TreeNode root) {
        List result = new ArrayList();
        if(root == null) return result;
        
        Queue queue = new LinkedList<>();
        queue.offer(root);
       
        while (!queue.isEmpty()) {
            int queue_size = queue.size();
            int max_value = Integer.MIN_VALUE;
            for (int i = 0; i < queue_size; i++) {
                TreeNode cur = queue.poll();
                max_value = Math.max(cur.val, max_value);
                if (cur.left != null) queue.add(cur.left);
                if (cur.right != null) queue.add(cur.right);
            }
            result.add(max_value);
        }
        return result;
    }
}

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