PisecesPeng / PisecesPeng.record.me

:beach_umbrella: All things are difficult before they are easy
MIT License
3 stars 1 forks source link

二叉树的层序遍历 #29

Closed PisecesPeng closed 3 years ago

PisecesPeng commented 3 years ago

二叉树的层序遍历

给你一个二叉树,
请你返回其按层序遍历得到的节点值.(即逐层地,从左到右访问所有节点).

示例:

二叉树:[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]


题目地址: https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

PisecesPeng commented 3 years ago

解题思路

代码

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;
    }

}
public static List<List<Integer>> func(TreeNode root) {
   List<TreeNode> tmpList = new ArrayList<>();
   if (null != root) tmpList.add(root);

   List<List<Integer>> x = new ArrayList<>();  // 存放结果
   while (tmpList.size() > 0) {
       // 将本层的节点复制到新list中, 并将老list清空
       List<TreeNode> tmp = new ArrayList();
       tmp.addAll(tmpList);
       tmpList.clear();
       List<Integer> y = new ArrayList<>();
       for (TreeNode node : tmp) {
           // 将本层的值统计
           y.add(node.val);
           // 将本层的节点按顺序添加, 为下一次循环
           if (null != node.left)
               tmpList.add(node.left);
           if (null != node.right)
               tmpList.add(node.right);
       }
       x.add(y);
   }
   return x;
}
PisecesPeng commented 3 years ago

LeetCode题解

解题思路

代码

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;
    }

}
public static List<List<Integer>> func(TreeNode root) {
    List<List<Integer>> ret = new ArrayList<List<Integer>>();
    if (root == null) {
        return ret;
    }

    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        List<Integer> level = new ArrayList<Integer>();
        int currentLevelSize = queue.size();
        for (int i = 1; i <= currentLevelSize; ++i) {
            TreeNode node = queue.poll();
            level.add(node.val);
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        ret.add(level);
    }

    return ret;
}