您的位置:首页 > 其它

Leetcode-Binary Tree Level Order Traversal II

2014-11-09 00:45 351 查看
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]
]

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

Solution:

/**
* Definition for binary tree
* 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>> res = new ArrayList<List<Integer>>();
if (root==null)
return res;

//Visit all node by using BFS.
List<TreeNode> queue = new ArrayList<TreeNode>();
List<Integer> depth = new ArrayList<Integer>();
queue.add(root);
depth.add(1);
int index = 0;
int curDepth = -1;
TreeNode curNode = null;
while (index<queue.size()){
curNode = queue.get(index);
curDepth = depth.get(index);
if (curNode.left!=null){
queue.add(curNode.left);
depth.add(curDepth+1);
}

if (curNode.right!=null){
queue.add(curNode.right);
depth.add(curDepth+1);
}

index++;
}

//Get the max depth, which is the number of lists in the result.
int maxDepth = depth.get(depth.size()-1);
for (int i=0;i<maxDepth;i++)
res.add(new ArrayList<Integer>());

//Put the value of each node into the corresponding list in the result.
for (int i=0;i<queue.size();i++){
curNode = queue.get(i);
curDepth = depth.get(i);
index = maxDepth-curDepth;
List<Integer> tempList = res.get(index);
tempList.add(curNode.val);
}

return res;
}
}


Using BFS to visit and record every tree node and its depth. Then put the value in each tree node into corresponding level list.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: