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 Traversal题的基础上进行修改得到的,只是在代码中加入了一条语句(对List进行逆序操作)。

相关知识点
Collections.reverse(list);//对list进行逆序操作


自己的代码
package leetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/*class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}*/

public class BinaryTreeLevelOrderTraversalII {
	public List<List<Integer>> levelOrder(TreeNode root) {
		List<List<Integer>> list = new ArrayList<List<Integer>>();
		
		if(root == null) return list;
		
		Queue<TreeNode> queue1 = new LinkedList<TreeNode>();
		Queue<TreeNode> queue2 = new LinkedList<TreeNode>();
		queue2.add(root);
		
		while(!queue2.isEmpty()){
			queue1.addAll(queue2);
			queue2.clear();
			List<Integer> tempList = new ArrayList<Integer>();
			while(!queue1.isEmpty()){
				TreeNode head = queue1.poll();
				tempList.add(head.val);
				if(head.left != null) queue2.add(head.left);
				if(head.right != null) queue2.add(head.right);
			}
			//Collections.sort(tempList);
			list.add(tempList);
		}
		
		Collections.reverse(list);
		
        return list; 
    }
	
	public static void main(String[] args) {
		TreeNode node1 = new TreeNode(3);
		TreeNode node2 = new TreeNode(9);
		TreeNode node3 = new TreeNode(20);
		TreeNode node4 = new TreeNode(15);
		TreeNode node5 = new TreeNode(17);
		
		node1.left = node2;
		node1.right = node3;
		node3.left = node4;
		node3.right = node5;
		
		BinaryTreeLevelOrderTraversalII btot = new BinaryTreeLevelOrderTraversalII();
		System.out.println(btot.levelOrder(node1).toString());
	}
}

你可能感兴趣的:(binary)