107. 二叉树的层序遍历 II

107. 二叉树的层序遍历 II

解题思路

  • 对二叉树的层序遍历进行改造
  • 自底向上进行遍历,只需要改写最后一步result.addFirst(list);
  • 将LinkedList双向链表作为栈来使用,先进入的层结果最后出来,那么最底层进来的层结果,最先出来,达到目的

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        // 二叉树的层序遍历进行改造
        LinkedList<List<Integer>> result = new LinkedList<>();
        if(root == null){
            return result;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        while(!q.isEmpty()){
            // 自底向上遍历
            // 计算队列的大小
            int size = q.size();
            List<Integer> list = new LinkedList<>();// 保存当前层遍历的所有节点
            for(int i = 0; i < size; i++){
                TreeNode cur = q.poll();// 对头出队
                list.add(cur.val);
                if(cur.left != null){
                    q.offer(cur.left);
                }

                if(cur.right != null){
                    q.offer(cur.right);
                }

            }

            // 将每一层的节点 添加到头部  那就成为了自底向上的层序遍历
            // 那么先进入的后出来  作为栈来使用
            result.addFirst(list);

        }


        return result;

    }
}

你可能感兴趣的:(#,Leetcode,数据结构)