给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if (root == null) {
return new ArrayList<>(0);
}
List<List<Integer>> ret = new ArrayList<>();
int deep = 0;
TreeNode curEnd = root, nextEnd = null;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
List<Integer> item;
if (ret.size() - 1 == deep) {
item = ret.get(deep);
} else {
item = new ArrayList<>();
ret.add(item);
}
item.add(cur.val);
if (cur.left != null) {
queue.offer(cur.left);
nextEnd = cur.left;
}
if (cur.right != null) {
queue.offer(cur.right);
nextEnd = cur.right;
}
if (cur == curEnd) {
deep++;
curEnd = nextEnd;
nextEnd = null;
}
}
Collections.reverse(ret);
return ret;
}
}
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;
}
}