首页 > 其他 > 详细

[LeetCode]Binary Tree Level Order Traversal II

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

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

样例:

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!