您的位置:首页 > 其它

leetcode第42题(binary-tree-level-order-traversal-ii)

2018-02-09 14:11 309 查看
题目:

Given a binary tree, return the bottom-up level ordertraversal 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],
]


confused what"{1,#,2,3}"means? > read more
on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below. 

Here's an example: 
1
/ \
2   3
/
4
\
5

The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}". 
4000

思路:

其实是树的层次遍历,只是每次是从底向上输出的答案的,因而在得到每层的结果时,添加的位置是list的头部。由于每层遍历是先输出左子树,再输出右子树的顺序,因而我们使用队列存储下一层的节点。

代码:

importjava.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(root==null){
return result;
}
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.add(root);
while(!que.isEmpty()){
int count = que.size();
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0;i<count;i++){
TreeNode node = que.poll();
list.add(node.val);
if(node.left!=null){
que.add(node.left);
}
if(node.right != null){
que.add(node.right);
}
}
result.add(0,list);
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: