【LeetCode刷题-树】-- 107.二叉树的层序遍历II

本文详细描述了如何用Java实现二叉树的层序遍历,从底层到顶层,采用队列和栈实现算法。
摘要由CSDN通过智能技术生成

107.二叉树的层序遍历II

image-20231211105723719

/**
 * 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>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<List<Integer>>();
        if(root==null){
            return ans;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            List<Integer> levelList = new ArrayList<>();
            int size = queue.size();
            for(int i = 0;i<size;i++){
                TreeNode now = queue.poll();
                levelList.add(now.val);
                if(now.left!=null){
                queue.offer(now.left);
                }
                if(now.right!=null){
                    queue.offer(now.right);
                }
            }
            //遍历完一层节点后,将存储该层节点值得列表添加到结果列表头部
            ans.add(0,levelList);
        }
        return ans;
    }
}
/**
 * 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>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<List<Integer>>();
        if(root==null){
            return ans;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        Stack<List<Integer>> stack = new Stack<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            List<Integer> levelList = new ArrayList<>();
            int size = queue.size();
            for(int i = 0;i<size;i++){
                TreeNode now = queue.poll();
                levelList.add(now.val);
                if(now.left!=null){
                queue.offer(now.left);
                }
                if(now.right!=null){
                    queue.offer(now.right);
                }
            }
            //定义一个栈,每次添加时入栈
            stack.push(levelList);
        }
        //弹出元素
        while(!stack.isEmpty()){
            ans.add(stack.pop());
        }
        return ans;
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值