赞
踩
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] ]
java:
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode(int x) { val = x; }
- * }
- */
- public class Solution {
-
- Queue<TreeNode> queue = new LinkedList<>();
- List<Integer> treeVal = new LinkedList<>();
- List<List<Integer>> res = new LinkedList<>();
-
- public List<List<Integer>> levelOrderBottom(TreeNode root)
- {
- if (root == null)
- return res;
- queue.add(root);
- treeVal.add(root.val);
- res.add(treeVal);
- while (!queue.isEmpty())
- {
- List<Integer> currVal = new LinkedList<>();
-
- //需要判断有多少个subtreeval e.t level2 有两个数值【2,3】
- //#############
- int len = queue.size();
- for(int i =0;i<len;i++)
- {
- TreeNode currNode = queue.poll();
- if (currNode.left != null)
- {
- currVal.add(currNode.left.val);
- queue.add(currNode.left);
- }
- if (currNode.right != null)
- {
- currVal.add(currNode.right.val);
- queue.add(currNode.right);
- }
- }
- if (!currVal.isEmpty())
- {
- res.add(currVal);
- }
-
- }
- Collections.reverse(res);
- return res;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。