Leetcode 107 Binary Tree Level Order Traversal II 层次遍历及其变形
题目分析
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]
]
层次遍历变形
显然这是一道典型的层次遍历问题,但是要求从最后一层开始遍历,直到第一层为止。对此的解决思路是首先由上而下进行遍历,再将遍历的结果翻转即可。
AC代码 (>98.67%)
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<TreeNode> queue = new ArrayList<>();
List<List<Integer>> result = new ArrayList<>();
if (root==null) return result;
queue.add(root);
int direct = 0;
while (!queue.isEmpty()){
List<Integer> addi = new ArrayList<>();
int num = queue.size();
for (int i=0;i<num;i++){
TreeNode node = queue.remove(0);
addi.add(node.val);
if (node.left!=null) queue.add(node.left);
if (node.right!=null) queue.add(node.right);
}
result.add(addi);
}
Collections.reverse(result);
return result;
}
}