Leetcode102.二叉树的层次遍历
非递归队列做法:
class Solution { public List<List<Integer>> levelOrder(TreeNode root) { ArrayList<List<Integer>> result = new ArrayList(); if(root == null){ return result; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); int level = 0; while ( !queue.isEmpty() ) { result.add(new ArrayList<Integer>()); int level_length = queue.size(); for(int i = 0; i < level_length; i++) { TreeNode node = queue.remove(); result.get(level).add(node.val); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } level++; } return result; } }递归:
ArrayList<List<Integer>> result = new ArrayList(); public void func(TreeNode node, int level) { if (result.size() == level) result.add(new ArrayList<Integer>()); result.get(level).add(node.val); if (node.left != null) func(node.left, level + 1); if (node.right != null) func(node.right, level + 1); } public List<List<Integer>> levelOrder(TreeNode root) { if (root == null) { return result; } func(root, 0); return result; }PS:递归的内存消耗居然要低于非递归,不知是不是测试样例的问题。。