zoukankan      html  css  js  c++  java
  • [二叉树的层序遍历(Leetcode 102)

    二叉树的层序遍历(Leetcode 102)

    数据结构定义:

    
     // Definition for a binary tree node.
      public class TreeNode {
          int val;
          TreeNode left;
          TreeNode right;
          TreeNode() {}
          TreeNode(int val) { this.val = val; }
          TreeNode(int val, TreeNode left, TreeNode right) {
              this.val = val;
              this.left = left;
              this.right = right;
          }
      }
    

    算法:

    //每次遍历都是一层数据
    //定义一个队列,队列初始的大小就是一层的数据大小
    //每次循环都从头拿数据,并将子树放入队列中
    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            LinkedList<TreeNode> queue =new LinkedList<>();
            if(root == null){
                return result;
            }
            queue.add(root);
            while(!queue.isEmpty()){
                int size = queue.size();
                List<Integer> temp =new ArrayList<>();
                for(int i =0;i<size;i++){
                    TreeNode node =queue.removeFirst();
                    temp.add(node.val);
                    if(node.left != null){
                        queue.add(node.left);
                    }
                    if(node.right != null){
                        queue.add(node.right);
                    }
                }
                result.add(temp);
            }
            return result;
            
        }
    }
    
  • 相关阅读:
    1924班网址
    20192414《网络空间安全导论》第一周学习总结
    H-Angry
    A-Plague Inc
    B-Rolling The Polygon
    F-Moving On
    A-Maximum Element In A Stack
    J-Word Search
    E-Pawns
    D-Lift Problems
  • 原文地址:https://www.cnblogs.com/CodingXu-jie/p/13895702.html
Copyright © 2011-2022 走看看