107 binary tree hierarchy traversal II

Title Description

Given a binary tree, the node returns its bottom-up value hierarchy traversal. (Ie, by physical layer to the layer from the leaf nodes of the root node, layer by layer traversal from left to right)

Ideas analysis

Or traverse the level of writing, non-recursive can recursively.
Finally Collections.reverse () Flip list, or use LinkedList when creating the list, use the api addFirst, each time increasing the list in the header.

Code

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        LinkedList<List<Integer>> arrayLists = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> arrayList = new ArrayList<>();
            int size = queue.size();
            while (size-- > 0) {
                TreeNode tmp = queue.poll();
                if (tmp == null) {
                    continue;
                }
                arrayList.add(tmp.val);
                queue.offer(tmp.left);
                queue.offer(tmp.right);
            }
            if (arrayList.size() != 0) {
                arrayLists.add(arrayList);
                //arrayLists.addFirst(arrayList);
            }
        }
        Collections.reverse(arrayLists);
        return arrayLists;
    }
Published 117 original articles · won praise 8 · views 3696

Guess you like

Origin blog.csdn.net/qq_34761012/article/details/104578433