标签:
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).
思路:
层次遍历 BFS
我的代码:
public class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> rst = new ArrayList<List<Integer>>(); if(root == null) return rst; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while(!queue.isEmpty()) { int size = queue.size(); List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < size; i++) { TreeNode node = queue.poll(); list.add(node.val); if(node.left != null) queue.offer(node.left); if(node.right != null) queue.offer(node.right); } rst.add(list); } Collections.reverse(rst); return rst; } }
他人代码:
public class Solution { public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (root == null) { return result; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); int currLevelNodeNum = 1; int nextLevelNodeNum = 0; while (currLevelNodeNum != 0) { ArrayList<Integer> currLevelResult = new ArrayList<Integer>(); nextLevelNodeNum = 0; while (currLevelNodeNum != 0) { TreeNode node = queue.poll(); currLevelNodeNum--; currLevelResult.add(node.val); if (node.left != null) { queue.offer(node.left); nextLevelNodeNum++; } if (node.right != null) { queue.offer(node.right); nextLevelNodeNum++; } } result.add(0, currLevelResult); currLevelNodeNum = nextLevelNodeNum; } return result; } }
学习之处:
Binary Tree Level Order Traversal II
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4328935.html