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);
}
} Question : Given an array of integers A, return the largest integer that only occurs once.…
Jump search algorithm is a pretty new algorithm to search for an element in a…
What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…
Binary Search is a Logarithmic search which finds the target element in a sorted array…
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…
This website uses cookies.