0107. Binary Tree Level Order Traversal Ii

107. Binary Tree Level Order Traversal II #

题目 #

给定二叉树的根节点 root,返回其节点值 自底向上的层序遍历

从叶子节点所在层到根节点所在的层,逐层从左向右遍历。

思路 #

  • 队列的栈: 先建栈,后出栈

代码 #

递归 #

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<>();
        if (root == null) return ans;
        
        Stack<Queue<TreeNode>> stack = new Stack<>();
        stack.push(new LinkedList<>());
        stack.peek().offer(root);
        
        boolean traversalNotEnd = true;
        while (traversalNotEnd == true) {
            traversalNotEnd = false;
            
            Queue<TreeNode> queue = stack.peek();
            stack.push(new LinkedList<>());
            for (TreeNode node: queue) {
                if (node.left == null && node.right == null) continue;
                if (node.left != null) stack.peek().offer(node.left);
                if (node.right != null) stack.peek().offer(node.right);
                traversalNotEnd = true;
            }
            
            if (traversalNotEnd == false) stack.pop();
        }
        
        while (stack.size() != 0) {
            Queue<TreeNode> queue = stack.pop();
            ans.add(new LinkedList<>());
            for (TreeNode node:queue) ans.get(ans.size() - 1).add(node.val);
        }
        
        return ans;
    }
}