[leetcode] Average of Levels in Binary Tree

임택·2021년 3월 5일
0

알고리즘

목록 보기
48/63

problem

code

1st try: DFS

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var averageOfLevels = function(root) {
    const sum = [];
    const count = [];
    recur(sum, count, root, 0);
    return sum.map((total, i) => total / count[i]);
};
const recur = (sum, count, node, level) => {
    if (node == null) return;
    sum[level] = sum[level] ? sum[level] + node.val : node.val;
    count[level] = count[level] ? count[level] + 1 : 1;
    level++;
    recur(sum, count, node.left, level);
    recur(sum, count, node.right, level)
}

Time: O(N)
Space: O(hegith of a tree), maximum number of level

2nd try: bfs - leetcode


/**
 * 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 < Double > averageOfLevels(TreeNode root) {
        List < Double > res = new ArrayList < > ();
        Queue < TreeNode > queue = new LinkedList < > ();
        queue.add(root);
        while (!queue.isEmpty()) {
            long sum = 0, count = 0;
            Queue < TreeNode > temp = new LinkedList < > ();
            while (!queue.isEmpty()) {
                TreeNode n = queue.remove();
                sum += n.val;
                count++;
                if (n.left != null)
                    temp.add(n.left);
                if (n.right != null)
                    temp.add(n.right);
            }
            queue = temp;
            res.add(sum * 1.0 / count);
        }
        return res;
    }
}

Time: O(N)
Space: O(M), M refers to the maximum mumber of nodes at any level in the input tree

profile
캬-!

0개의 댓글