Solution in Java


  • 0
    A

    /**

    • 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) {
      List<List<Integer>> list = new ArrayList();
      levelOrderBottom(0, root, list);
      List<List<Integer>> reverse = new ArrayList();
      for(int i = list.size() - 1; i >= 0; i--) {
      // System.out.println(i + " " + list.get(i));
      reverse.add(list.get(i));
      }
      return reverse;
      }

      private void levelOrderBottom(int i, TreeNode root, List<List<Integer>> list) {
      if(root != null) {
      if(i < list.size()) {
      List temp = list.get(i);
      temp.add(root.val);
      list.set(i, temp);
      } else
      {
      List temp = new ArrayList();
      temp.add(root.val);
      list.add(temp);
      }
      levelOrderBottom(i + 1, root.left, list);
      levelOrderBottom(i + 1, root.right, list);
      }
      }
      }


Log in to reply
 

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