给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 例如:给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7返回其层次遍历结果: [ [3], [9,20], [15,7]]
1 /* 2 思路1 : 用两个链表分别代替两个层次,交替使用 3 */ 4 public List<List<Integer>> levelOrder(TreeNode root) { 5 List<List<Integer>> res = new ArrayList<>(); 6 if (root == null) { 7 return res; 8 } 9 List<TreeNode> list1 = new LinkedList<>(); 10 List<TreeNode> list2 = new LinkedList<>(); 11 list1.add(root); 12 while (list1.size() != 0 || list2.size() != 0) { 13 List<TreeNode> notEmptyList = list1.size() == 0 14 ? list2 15 : list1; 16 List<TreeNode> emptyList = list1.size() == 0 17 ? list1 18 : list2; 19 List<Integer> resList = new LinkedList<>(); 20 while (notEmptyList.size() != 0) { 21 TreeNode temp = notEmptyList.remove(0); 22 resList.add(temp.val); 23 if (temp.left != null) { 24 emptyList.add(temp.left); 25 } 26 if (temp.right != null) { 27 emptyList.add(temp.right); 28 } 29 } 30 res.add(resList); 31 } 32 return res; 33 }
1 /* 2 思路2 : 直接层次遍历 3 */ 4 public List<List<Integer>> levelOrder_1(TreeNode root) { 5 List<List<Integer>> res = new ArrayList<>(); 6 if (root == null) { 7 return res; 8 } 9 LinkedList<TreeNode> list = new LinkedList<>(); 10 list.add(root); 11 int currLevelNodes = 1; 12 while (list.size() != 0) { 13 LinkedList<Integer> resList = new LinkedList<>(); 14 currLevelNodes = list.size(); 15 for (int i = currLevelNodes; i > 0; --i) { 16 TreeNode removeNode = list.remove(); 17 resList.add(removeNode.val); 18 if (removeNode.left != null) { 19 list.add(removeNode.left); 20 } 21 if (removeNode.right != null) { 22 list.add(removeNode.right); 23 } 24 } 25 res.add(resList); 26 } 27 return res; 28 }
1 /* 2 思路3 : 递归层次遍历 3 */ 4 public List<List<Integer>> levelOrder_2(TreeNode root) { 5 List<List<Integer>> res = new ArrayList<>(); 6 search(root, 0, res); 7 return res; 8 } 9 10 private void search(TreeNode parent, int level, List<List<Integer>> res) { 11 if (parent == null) { 12 return; 13 } 14 if (res.size() <= level) { 15 res.add(new ArrayList<>()); 16 } 17 res.get(level).add(parent.val); 18 search(parent.left, level + 1, res); 19 search(parent.right, level + 1, res); 20 }
原文地址:https://www.cnblogs.com/rainbow-/p/10360102.html
时间: 2024-11-08 01:19:23