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

LeetCode——Binary Tree Level Order Traversal II

时间:2014-07-14 17:31:14      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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]
]
原题链接:https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/

题目:给定一个二叉树,从底到顶返回节点的层序遍历的值。(如,从左到右,一层一层)

思路:上一题的结果上面逆转一下即可。完全不用出这题吧?

	public List<List<Integer>> levelOrderBottom(TreeNode root) {
		List<List<Integer>> list = new ArrayList<List<Integer>>();
		if (root == null)
			return list;
		Queue<TreeNode> queue = new LinkedList<TreeNode>();
		queue.add(root);
		while (!queue.isEmpty()) {
			List<Integer> li = new ArrayList<Integer>();
			int size = queue.size();
			for (int i = 0; i < size; i++) {
				TreeNode node = queue.poll();
				li.add(node.val);
				if (node.left != null)
					queue.add(node.left);
				if (node.right != null)
					queue.add(node.right);
			}
			list.add(li);
		}
		List<List<Integer>> ret = new ArrayList<List<Integer>>();
		for (int i = list.size() - 1; i >= 0; i--) {
			ret.add(list.get(i));
		}
		return ret;
	}

	// Definition for binary tree
	public class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;

		TreeNode(int x) {
			val = x;
		}
	}




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

LeetCode——Binary Tree Level Order Traversal II

标签:leetcode

原文地址:http://blog.csdn.net/laozhaokun/article/details/37757409

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