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

107.二叉树的层序遍历II

【LeetCode刷题-树】-- 107.二叉树的层序遍历II_第1张图片

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

你可能感兴趣的:(#,二叉树,leetcode,算法)