您的位置:首页 > 其它

[LeetCode]Binary Tree Level Order Traversal II

2015-09-21 11:17 471 查看
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]
]


题解:采用的是bfs+queue,queue使用list来模拟的,jdk1.8 LinkedList没有实现Queue,最后用Collections.reverse(list)反转,用parentSize和childSize来统计一行的节点数。

code:

public List<List<Integer>> levelOrderBottom(TreeNode root) {

		List<List<Integer>> level = new ArrayList<List<Integer>>();
		List<Integer> con = new ArrayList<Integer>();
		TreeNode temp;
		int parentSize=1;
		int childSize=0;
		List<TreeNode> q = new LinkedList<TreeNode>();
		q.add(root);
		do{
			temp = q.get(0);
			con.add(temp.val);
			q.remove(0);
			if(temp.left!=null){
				
				q.add(temp.left);
				childSize++;
			}
			if(temp.right!=null){
				q.add(temp.right);
				childSize++;
			}
			parentSize--;
			if(parentSize ==0){
				
				level.add(con);
				parentSize = childSize;
				childSize=0;
				con = new ArrayList<Integer>();
			}
			
		}while(!q.isEmpty());
		Collections.reverse(level);
		return level;
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: