107. Binary Tree Level Order Traversal II
Binary Tree Level Order Traversal II
3Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
Stack<List<Integer>> stack = new Stack<>();
List<TreeNode> cur = new ArrayList<>();
cur.add(root);
while (!cur.isEmpty()) {
stack.add(cur.stream().map(item->item.val).collect(Collectors.toList()));
List<TreeNode> nextLevel = new ArrayList<>();
cur.forEach(item -> {
if (item.left != null) {
nextLevel.add(item.left);
}
if (item.right != null) {
nextLevel.add(item.right);
}
});
cur = null;
cur = nextLevel;
}
List<List<Integer>> result = new ArrayList<>();
while (!stack.isEmpty()) {
result.add(stack.pop());
}
return result;
}
}Previous106. Construct Binary Tree from Inorder and Postorder TraversalNext108. Convert Sorted Array to Binary Search Tree
Last updated