102Binary Tree Level Order Traversal

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了102Binary Tree Level Order Traversal相关的知识,希望对你有一定的参考价值。

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<List<Integer>> levelOrder(TreeNode root) {
12         List<List<Integer>> returnVal = new ArrayList<List<Integer>>();
13         if (root == null)
14             return returnVal;
15         Queue<TreeNode> nodes = new ArrayDeque<TreeNode>();
16         nodes.offer(root);
17         
18         Queue<TreeNode> nextLevel = new ArrayDeque<TreeNode>();
19         
20         List<Integer> currentList = new ArrayList<Integer>();
21         while(!nodes.isEmpty())
22         {
23             TreeNode next = nodes.poll();
24             currentList.add(next.val);
25             if(next.left != null)
26                 nextLevel.offer(next.left);
27             if(next.right != null)
28                 nextLevel.offer(next.right);
29             
30             if(nodes.isEmpty())
31             {
32                 nodes = nextLevel;
33                 nextLevel = new ArrayDeque<TreeNode>();
34                 returnVal.add(currentList);
35                 currentList = new ArrayList<Integer>();
36             }
37         }
38         
39         
40         return returnVal;
41     }
42 }

 

以上是关于102Binary Tree Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章

102. Binary Tree Level Order Traversal

LeetCode102. Binary Tree Level Order Traversal

102Binary Tree Level Order Traversal

102. Binary Tree Level Order Traversal

Leetcode 102. Binary Tree Level Order Traversal

[LeetCode]题解(python):102 Binary Tree Level Order Traversal