|
| 1 | +##### 题目 |
| 2 | +``` |
| 3 | +给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 |
| 4 | +
|
| 5 | +例如: |
| 6 | +给定二叉树: [3,9,20,null,null,15,7], |
| 7 | +
|
| 8 | + 3 |
| 9 | + / \ |
| 10 | + 9 20 |
| 11 | + / \ |
| 12 | + 15 7 |
| 13 | +
|
| 14 | +返回其层次遍历结果: |
| 15 | +
|
| 16 | +[ |
| 17 | + [3], |
| 18 | + [9,20], |
| 19 | + [15,7] |
| 20 | +] |
| 21 | +
|
| 22 | +
|
| 23 | +``` |
| 24 | +##### 代码 |
| 25 | +循环 |
| 26 | +``` |
| 27 | +/** |
| 28 | + * Definition for a binary tree node. |
| 29 | + * public class TreeNode { |
| 30 | + * int val; |
| 31 | + * TreeNode left; |
| 32 | + * TreeNode right; |
| 33 | + * TreeNode(int x) { val = x; } |
| 34 | + * } |
| 35 | + */ |
| 36 | +class Solution { |
| 37 | + public List<List<Integer>> levelOrder(TreeNode root) { |
| 38 | + List<List<Integer>> resList=new ArrayList<>(); |
| 39 | + Queue<TreeNode> queue=new LinkedList<>(); |
| 40 | + if (root==null) { |
| 41 | + return resList; |
| 42 | + } |
| 43 | +
|
| 44 | + queue.offer(root); |
| 45 | + while(!queue.isEmpty()){ |
| 46 | + int length=queue.size(); |
| 47 | + List<Integer> tempList=new ArrayList<>(); |
| 48 | + for (int i=0; i<length; i++) { |
| 49 | + if (queue.peek().left!=null) { |
| 50 | + queue.offer(queue.peek().left); |
| 51 | + } |
| 52 | + if (queue.peek().right!=null) { |
| 53 | + queue.offer(queue.peek().right); |
| 54 | + } |
| 55 | + tempList.add(queue.poll().val); |
| 56 | + } |
| 57 | + resList.add(tempList); |
| 58 | + } |
| 59 | + return resList; |
| 60 | + } |
| 61 | +} |
| 62 | +``` |
| 63 | +递归 |
| 64 | + |
| 65 | +``` |
| 66 | +/** |
| 67 | + * Definition for a binary tree node. |
| 68 | + * public class TreeNode { |
| 69 | + * int val; |
| 70 | + * TreeNode left; |
| 71 | + * TreeNode right; |
| 72 | + * TreeNode(int x) { val = x; } |
| 73 | + * } |
| 74 | + */ |
| 75 | +class Solution { |
| 76 | + public List<List<Integer>> levelOrder(TreeNode root) { |
| 77 | + List<List<Integer>> res = new ArrayList<List<Integer>>(); |
| 78 | + levelOrderHelper(res, root, 0); |
| 79 | + return res; |
| 80 | + } |
| 81 | +
|
| 82 | + public void levelOrderHelper(List<List<Integer>> res,TreeNode root,int length){ |
| 83 | + if (root==null) { |
| 84 | + return; |
| 85 | + } |
| 86 | + if (length>=res.size()) { |
| 87 | + res.add(new ArrayList<Integer>()); |
| 88 | + } |
| 89 | + res.get(length).add(root.val); |
| 90 | + levelOrderHelper(res,root.left,length+1); |
| 91 | + levelOrderHelper(res,root.right,length+1); |
| 92 | + } |
| 93 | +
|
| 94 | +} |
| 95 | +``` |
0 commit comments