107. Binary Tree Level Order Traversal II | 层次遍历顺序逆置输出

来源:互联网 发布:中英文域名注册 编辑:程序博客网 时间:2024/06/01 09:31

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]]

Subscribe to see which companies asked this question.


思路:用两个变量记录在层次遍历时,当前层的数量和下一层的数量。


/** * 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) {List<List<Integer>> levellist = new ArrayList<>();if (root == null) {return levellist;}int curr, next;curr = 1;next = 0;LinkedList<TreeNode> queue = new LinkedList<>();queue.addLast(root);List<Integer> list = new ArrayList<>();while (!queue.isEmpty()) {TreeNode t = queue.pop();if (t != null) {list.add(t.val);curr--;}if (t.left != null) {queue.addLast(t.left);next++;}if (t.right != null) {queue.addLast(t.right);next++;}if (curr == 0) {levellist.add(0,list);list = new ArrayList<>();curr = next;next = 0;}}return levellist;}}




0 0
原创粉丝点击