声明:问题描述来源leetcode
难度中等626
给你二叉树的根节点 root
,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[15,7],[9,20],[3]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
[0, 2000]
内-1000 <= Node.val <= 1000
/**
* Definition for a binary tree node.
* public 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;
* }
* }
*/
class Solution {
List<List<Integer>> lists = new LinkedList<>();
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if (root == null) return lists;
lists.add(new LinkedList<>());
searchGoalByOrder(0,root);
Collections.reverse(lists);
return lists;
}
private void searchGoalByOrder(int order, TreeNode root) {
lists.get(order).add(root.val);
if (root.left != null){
if (order + 1 > lists.size() - 1) lists.add(new LinkedList<>());
searchGoalByOrder(order + 1,root.left);
}
if (root.right != null){
if (order + 1 > lists.size() - 1) lists.add(new LinkedList<>());
searchGoalByOrder(order + 1,root.right);
}
}
}
end
思路和层序遍历的一样,先按照层序遍历的思路整出一个正序的链表,再通过调用Collections的API来反转该链表。