跳至主要內容

637, 二叉树的层平均值

Mike大约 4 分钟binary treeeasybinary treedepth first searchbreadth first search

一、题目描述

给定一个非空二叉树的根节点root,以数组的形式返回每一层节点的平均值。与实际答案相差10⁻⁵以内的答案可以被接受。

示例 1
5 nodes
输入: root = [3, 9, 20, null, null, 15, 7]
输出: [3.00000, 14.50000, 11.00000]
解释: 第0层的平均值为3,第1层的平均值为14.5,第2层的平均值为11。因此返回[3, 14.5, 11]。

示例 2
5 nodes
输入: root = [3, 9, 20, 15, 7]
输出: [3.00000, 14.50000, 11.00000]

提示

  • 树中节点数量在[1, 10⁴]范围内
  • -2³¹ <= Node.val <= 2³¹ - 1

相关主题

  • 深度优先搜索
  • 广度优先搜索
  • 二叉树

二、题解

#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Rc<RefCell<TreeNode>>>,
    pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
    #[inline]
    pub fn new(val: i32) -> Self {
        TreeNode {
            val,
            left: None,
            right: None,
        }
    }
}

方法 1: 深度优先搜索

pub fn average_of_levels(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
    //Self::dfs_recursion(root)
    Self::dfs_iteration(root)
}

///
/// DFS - Recursion
///
fn dfs_recursion(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
    let mut level_sum = vec![];
    const PRE_ORDER: fn(Option<Rc<RefCell<TreeNode>>>, usize, &mut Vec<(usize, i64)>) =
        |root, level, level_sum| {
            if let Some(curr) = root {
                if level == level_sum.len() {
                    level_sum.push((0, 0));
                }
                level_sum[level].0 += 1;
                level_sum[level].1 += curr.borrow().val as i64;
                
                PRE_ORDER(curr.borrow_mut().left.take(), level + 1, level_sum);
                PRE_ORDER(curr.borrow_mut().right.take(), level + 1, level_sum);
            }
        };

    PRE_ORDER(root, 0, &mut level_sum);

    level_sum
        .into_iter()
        .map(|(count, sum)| sum as f64 / count as f64)
        .collect()
}

///
/// DFS - Iteration
///
fn dfs_iteration(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
    let mut level_sum = vec![];

    if let Some(root) = root {
        let mut stack = vec![Ok((root, 0))];
        while let Some(curr) = stack.pop() {
            match curr {
                Ok((node, level)) => {
                    if let Some(right) = node.borrow_mut().right.take() {
                        stack.push(Ok((right, level + 1)));
                    }
                    if let Some(left) = node.borrow_mut().left.take() {
                        stack.push(Ok((left, level + 1)));
                    }
                    stack.push(Err((node.borrow().val, level)));
                }
                Err((val, level)) => {
                    if level == level_sum.len() {
                        level_sum.push((0_usize, 0_i64));
                    }
                    level_sum[level].0 += 1;
                    level_sum[level].1 += val as i64;
                }
            }
        }
    }

    level_sum
        .into_iter()
        .map(|(count, sum)| sum as f64 / count as f64)
        .collect()
}

方法 2: 广度优先搜索

pub fn average_of_levels(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
    //Self::bfs_iteration_1(root)
    Self::bfs_iteration_2(root)
}

///
/// BFS - Iteration
///
fn bfs_iteration_1(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
    let mut res = vec![];

    if let Some(root) = root {
        let mut queue = VecDeque::from([(root, 0)]);
        let mut level_sum = (0_usize, 0_i64);
        let mut curr_level = 0;

        while let Some((curr, level)) = queue.pop_front() {
            if level != curr_level {
                res.push(level_sum.1 as f64 / level_sum.0 as f64);
                level_sum.0 = 0;
                level_sum.1 = 0;
            }
            level_sum.0 += 1;
            level_sum.1 += curr.borrow().val as i64;
            curr_level = level;

            if let Some(left) = curr.borrow_mut().left.take() {
                queue.push_back((left, level + 1));
            }
            if let Some(right) = curr.borrow_mut().right.take() {
                queue.push_back((right, level + 1));
            }
        }

        res.push(level_sum.1 as f64 / level_sum.0 as f64);
    }

    res
}

///
/// BFS - Iteration
///
fn bfs_iteration_2(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
    let mut res = vec![];

    if let Some(root) = root {
        let mut queue = VecDeque::from([root]);

        while !queue.is_empty() {
            let level_len = queue.len();
            let mut level_sum = 0_i64;

            for _ in 1..=level_len {
                if let Some(curr) = queue.pop_front() {
                    level_sum += curr.borrow().val as i64;

                    if let Some(left) = curr.borrow_mut().left.take() {
                        queue.push_back(left);
                    }
                    if let Some(right) = curr.borrow_mut().right.take() {
                        queue.push_back(right);
                    }
                }
            }

            res.push(level_sum as f64 / level_len as f64);
        }
    }

    res
}