515 Find Largest Value in Each Tree Row

1. Question

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]

2. Implementation

(1) BFS

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<>();

        if (root == null) {
            return res;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int curMax = Integer.MIN_VALUE, size = 0;

        while (!queue.isEmpty()) {
            size = queue.size();
            curMax = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.remove();

                curMax = Math.max(curMax, curNode.val);

                if (curNode.left != null) {
                    queue.add(curNode.left);
                }

                if (curNode.right != null) {
                    queue.add(curNode.right);
                }
            }
            res.add(curMax);
        }
        return res;
    }
}

(2) DFS

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<>();

        if (root == null) {
            return res;
        }

        getLargestValues(root, 0, res);
        return res;
    }

    public void getLargestValues(TreeNode node, int depth, List<Integer> res) {
        if (node == null) {
            return;
        }

        if (res.size() <= depth) {
            res.add(node.val);
        }
        else if (res.get(depth) < node.val) {
            res.set(depth, node.val);
        }

        getLargestValues(node.left, depth + 1, res);
        getLargestValues(node.right, depth + 1, res);
    }
}

3. Time & Space Complexity

BFS: 时间复杂度是O(n), 空间复杂度是O(Math.max(h, w)), h是树的高度,w是树的一层中包含最多node的个数

DFS:时间复杂度是O(n), 空间复杂度是O(h)

Last updated