Data Structures & Algorithms

Leetcode Binary Tree Level Order Traversal II Java Solution

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:
We can solve it multiple ways using Breadth First Search and Depth First Search the below solution uses Depth First Search with Back Tracking.

class HackerHeap {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
         List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (root == null) {
            return result;
        }
        dfs(root, 0, result);
        return result;
    }
    public void dfs(TreeNode root, int level, List<List<Integer>> rst) {
        if (root == null) {
            return;
        }
        if (level >= rst.size()) {
            rst.add(0, new ArrayList<Integer>());
        }
        dfs(root.left, level + 1, rst);
        dfs(root.right, level + 1, rst);
        rst.get(rst.size() - level - 1).add(root.val);
    }
}
rajendra

Recent Posts

Largest Unique Number Java Solution

Question : Given an array of integers A, return the largest integer that only occurs once.…

9 months ago

Jump Search Algorithm In Java

Jump search algorithm is a pretty new algorithm to search for an element in a…

1 year ago

Knuth Morris Pratt Pattern Search Algorithm

What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…

1 year ago

Binary Search Algorithm In Java

Binary Search is a Logarithmic search which finds the target element in a sorted array…

1 year ago

Leetcode Integer to Roman Java Solution

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…

2 years ago

Leetcode Container With Most Water Java Solution

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…

2 years ago

This website uses cookies.