1. 程式人生 > >【leetcode】【107】Binary Tree Level Order Traversal II

【leetcode】【107】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]
]

二、問題分析

三、Java AC程式碼

public List<List<Integer>> levelOrderBottom(TreeNode root) {
        LinkedList<List<Integer>> list = new LinkedList<List<Integer>>();
		if (root==null) {
			return list;
		}
		LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
		LinkedList<Integer> listItem = new LinkedList<Integer>();
		queue.add(root);
		int curLevelItemNums = 1;
		int nextLevelItemNums = 0;
		while(!queue.isEmpty()){
			TreeNode node = queue.poll();
			TreeNode leftNode = node.left;
			TreeNode rightNode = node.right;
			curLevelItemNums--;
			listItem.add(node.val);
			if (leftNode!=null) {
				queue.add(leftNode);
				nextLevelItemNums++;
			}
			if (rightNode!=null) {
				queue.add(rightNode);
				nextLevelItemNums++;
			}
			if (curLevelItemNums == 0) {
				curLevelItemNums = nextLevelItemNums;
				nextLevelItemNums = 0;
				list.push(listItem);
				listItem = new LinkedList<Integer>();
			}
		}
		return list;
    }