Problem

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:
Given binary tree

          1
         / \
        2   3
       / \     
      4   5

Returns[4, 5, 3], [2], [1].

Explanation:

  1. Removing the leaves[4, 5, 3]would result in this tree:
          1
         / 
        2
  1. Now removing the leaf[2]would result in this tree:
          1
  1. Now removing the leaf[1]would result in the empty tree:
          []

Returns[4, 5, 3], [2], [1].

思路一(直接divide & conquer)

  • 得到左右子树的结果, 合并
    public List<List<Integer>> findLeaves(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;

        List<List<Integer>> left = findLeaves(root.left);
        List<List<Integer>> right = findLeaves(root.right);

        List<List<Integer>> big;
        List<List<Integer>> small;
        if (left.size() >= right.size()) {
            big = left;
            small = right;
        } else {
            big = right;
            small = left;
        }

        for (int i = 0; i < big.size(); i++) {
            List<Integer> list = new ArrayList<>();
            list.addAll(big.get(i));
            if (i < small.size())
                list.addAll(small.get(i));
            res.add(list);
        }
        List<Integer> self = new ArrayList<>();
        self.add(root.val);
        res.add(self);

        return res;
    }

思路二(间接divide & conquer)

  • bottom up to calculate the height of each node, then height(leave ) = 1
    public List<List<Integer>> findLeaves(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        height(root, res);
        return res;
    }

    private int height(TreeNode root, List<List<Integer>> res) {
        if (root == null) return -1;

        int level = 1 + Math.max(height(root.left, res), height(root.right, res));
        if (res.size() < level + 1) res.add(new ArrayList<Integer>());
        res.get(level).add(root.val);
        return level;
    }

results matching ""

    No results matching ""