`
huntfor
  • 浏览: 201259 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode]Binary Tree Level Order Traversal II

 
阅读更多

新博文地址:

[leetcode]Binary Tree Level Order Traversal II

Binary Tree Level Order Traversal II

 

写道
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],
]

 实在看不出来跟Binary Tree Level Order Traversa有啥本质区别。。。所以我偷懒,在原来的基础上加了一个stack。。。。算法完全一样。o(╯□╰)o,接受大家的鄙视。

 

	ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
	Stack<ArrayList<Integer>> stack = new Stack<ArrayList<Integer>>();
	public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
		if(root == null){
			return result;
		}
		ArrayDeque<TreeNode> pre = new ArrayDeque<TreeNode>();
		ArrayDeque<TreeNode> post= new ArrayDeque<TreeNode>();
		pre.offer(root);
		ArrayList<Integer> rootList = new ArrayList<Integer>(Arrays.asList(root.val));
		stack.push(rootList);
		while(!pre.isEmpty()){
			TreeNode tem = pre.poll();
			if(tem.left!=null){
				post.offer(tem.left);
			}
			if(tem.right!=null){
				post.offer(tem.right);
			}
			if(pre.isEmpty()){
				if(post.isEmpty()){
					break;
				}
				pre = post.clone();
				post.clear();
				ArrayList<Integer> list = new ArrayList<Integer>();
				for(TreeNode node : pre){
					list.add(node.val);
				}
				stack.push(list);
			}
		}
		while(!stack.isEmpty()){
			ArrayList<Integer> list = stack.pop();
			result.add(list);
		}
		return result;	
	}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics