Java BFS solution reuse level order traversal


  • 0
    S

    Just reuse the level order traversal code and insert in beginning in the main list.

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            LinkedList<List<Integer>> result = new LinkedList();
            if(root == null) return result;
            LinkedList<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            while(queue.size() > 0) {
                List<Integer> list = new ArrayList();
                int size = queue.size();
                for(int i=0; i<size; i++) {
                    TreeNode element = queue.remove();
                    list.add(element.val);
                    if(element.left != null) queue.add(element.left);
                    if(element.right != null) queue.add(element.right);
                }
                result.addFirst(list);
            }
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.