366. Find Leaves of Binary Tree

Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.

 

Example:

Input: [1,2,3,4,5]
  
          1
         / \
        2   3
       / \     
      4   5    

Output: [[4,5,3],[2],[1]]

 

Explanation:

1. Removing the leaves [4,5,3] would result in this tree:

          1
         / 
        2          

 

2. Now removing the leaf [2] would result in this tree:

          1          

 

3. Now removing the leaf [1] would result in the empty tree:

          []         
[[3,5,4],[2],[1]], [[3,4,5],[2],[1]], etc, are also consider correct answers since per each level it doesn't matter the order on which elements are returned.

Rust Solution

struct Solution;
use rustgym_util::*;

trait Postorder {
    fn postorder(&self, leaves: &mut Vec<Vec<i32>>) -> usize;
}

impl Postorder for TreeLink {
    fn postorder(&self, leaves: &mut Vec<Vec<i32>>) -> usize {
        if let Some(node) = self {
            let left = node.borrow().left.postorder(leaves);
            let right = node.borrow().right.postorder(leaves);
            let level = left.max(right) + 1;
            if leaves.len() < level {
                leaves.push(vec![node.borrow().val]);
            } else {
                leaves[level - 1].push(node.borrow().val);
            }
            level
        } else {
            0
        }
    }
}

impl Solution {
    fn find_leaves(root: TreeLink) -> Vec<Vec<i32>> {
        let mut res: Vec<Vec<i32>> = vec![];
        root.postorder(&mut res);
        res
    }
}

#[test]
fn test() {
    let root = tree!(1, tree!(2, tree!(4), tree!(5)), tree!(3));
    let res = vec![vec![4, 5, 3], vec![2], vec![1]];
    assert_eq!(Solution::find_leaves(root), res);
}

Having problems with this solution? Click here to submit an issue on github.