首页 > 其他分享 >102. Binary Tree Level Order Traversal

102. Binary Tree Level Order Traversal

时间:2022-11-19 19:13:21浏览次数:52  
标签:Binary Level res Tree queue add null root List

Solution 1: class Solution {     public List<List<Integer>> levelOrder(TreeNode root) {         Queue<TreeNode> queue = new LinkedList<>();         List<List<Integer>> wrapList = new LinkedList<>();         if(root == null)              return wrapList;         queue.offer(root);         while (!queue.isEmpty()) {             int levelNum = queue.size();             List<Integer> subList = new LinkedList<>();             for(int i = 0; i < levelNum; i++) {               TreeNode n = q.poll();           if(n.left != null) q.add(n.left);                 if(n.right != null) q.add(n.right);                 subList.add(n.val);             }             wrapList.add(subList);         }         return wrapList;     } }   //如果要求把null节点也列出来: public static List<List<Integer>> levelOrder(TreeNode root) {     Queue<TreeNode> queue = new LinkedList<>();     List<List<Integer>> wrapList = new LinkedList<>();     if(root == null)         return wrapList;     queue.offer(root);     while (!queue.isEmpty()) {         int levelNum = queue.size();         List<Integer> subList = new LinkedList<>();         for(int i = 0; i < levelNum; i++) {             TreeNode tn = queue.poll();             if(tn != null)                 queue.offer(tn.left);             if(tn != null)                 queue.offer(tn.right);             if (tn == null)                 subList.add(null);             else                 subList.add(tn.val);         }         wrapList.add(subList);     }     return wrapList; }     Solution 2: class Solution {    public List<List<Integer>> levelOrder(TreeNode root) {         List<List<Integer>> res = new ArrayList<>();         levelHelper(res, root, 0);         return res;     }          public void levelHelper(List<List<Integer>> res, TreeNode root, int height) {         if (root == null) return;         if (height >= res.size()) {             res.add(new LinkedList<>());         }         res.get(height).add(root.val);         levelHelper(res, root.left, height+1);         levelHelper(res, root.right, height+1);     } }

标签:Binary,Level,res,Tree,queue,add,null,root,List
From: https://www.cnblogs.com/MarkLeeBYR/p/16906775.html

相关文章