Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example: Given binary tree [3,9,20,null,null,15,7],

3

/ \ 9 20 / \ 15 7

return its bottom-up level order traversal as:

[ [15,7], [9,20], [3] ]

Solution

/**
 * 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<List<Integer>> levelOrderBottom(TreeNode root) {
            if (root == null) {
            return new ArrayList<>();
        }


        Stack<List<Integer>> stack = new Stack<>();
        List<TreeNode> cur = new ArrayList<>();
        cur.add(root);

        while (!cur.isEmpty()) {
            stack.add(cur.stream().map(item->item.val).collect(Collectors.toList()));

            List<TreeNode> nextLevel = new ArrayList<>();
            cur.forEach(item -> {
                if (item.left != null) {
                    nextLevel.add(item.left);
                }

                if (item.right != null) {
                    nextLevel.add(item.right);
                }
            });

            cur = null;
            cur = nextLevel;
        }

        List<List<Integer>> result = new ArrayList<>();
        while (!stack.isEmpty()) {
            result.add(stack.pop());
        }

        return result;
    }
}

results matching ""

    No results matching ""