码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Binary Tree Level Order Traversal II

时间:2014-07-29 14:42:48      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:style   java   color   os   io   for   ar   算法   

题目:给定一颗二叉树,求出对其层次遍历以后的逆序输出

样例:

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]
]
算法:深度优先搜索对二叉树进行层次遍历,判断节点的层次

public class Solution {
		ArrayList<List<Integer>> levelOrderList = new ArrayList<List<Integer>>();
		
		public List<List<Integer>> levelOrderBottom(TreeNode root) {
			dfs(root, 0);
			
			ArrayList<List<Integer>> levelOrderReverseList = new ArrayList<List<Integer>>();
			for (List<Integer> levelOrder : levelOrderList) {
				levelOrderReverseList.add(0, levelOrder);
			}
			return levelOrderReverseList;
		}
		
		public void dfs(TreeNode node, int height) {
			if (null == node) {
				return ;
			}
			
			if (levelOrderList.isEmpty() || levelOrderList.size()<height+1) {
				List<Integer> levelOrder = new ArrayList<Integer>();
				levelOrder.add(node.val);
				levelOrderList.add(height, levelOrder);
			} else if (levelOrderList.size() >= height+1) {
				List<Integer> levelOrder = levelOrderList.get(height);
				levelOrder.add(node.val);
			}
			dfs(node.left, height+1);
			dfs(node.right, height+1);
		}
	}

[LeetCode]Binary Tree Level Order Traversal II,布布扣,bubuko.com

[LeetCode]Binary Tree Level Order Traversal II

标签:style   java   color   os   io   for   ar   算法   

原文地址:http://blog.csdn.net/yeweiouyang/article/details/38235759

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!