LeetCode——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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]原题链接:https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/
题目:给定一个二叉树,从底到顶返回节点的层序遍历的值。(如,从左到右,一层一层)
思路:上一题的结果上面逆转一下就可以。全然不用出这题吧?
public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> list = new ArrayList<List<Integer>>(); if (root == null) return list; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); while (!queue.isEmpty()) { List<Integer> li = new ArrayList<Integer>(); int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); li.add(node.val); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } list.add(li); } List<List<Integer>> ret = new ArrayList<List<Integer>>(); for (int i = list.size() - 1; i >= 0; i--) { ret.add(list.get(i)); } return ret; } // Definition for binary tree public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }