Skip to content

Latest commit

 

History

History
72 lines (62 loc) · 1.61 KB

D-2 submission.md

File metadata and controls

72 lines (62 loc) · 1.61 KB

⚡ Question:

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]
 ]

🍑 My Solution:


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
 
 
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        List<List<Integer>> ans = new LinkedList<List<Integer>>();
        
        if(root == null){
         return ans;
        }
        queue.offer(root);
        while(!queue.isEmpty()){
            int level = queue.size();
            List<Integer> anslist = new LinkedList<Integer>();
            for(int i=0; i<level; i++) {
                if(queue.peek().left != null) 
                {
                    queue.offer(queue.peek().left);
                }
                if(queue.peek().right != null)
                {
                    queue.offer(queue.peek().right);
                }
                anslist.add(queue.poll().val);
            }
            ans.add(0, anslist);
        }

        return ans;      
    }
}