剑指 Offer 32 - III. 从上到下打印二叉树 III AND 31. 栈的压入、弹出序列

177 阅读1分钟

这是我参与8月更文挑战的第11天,活动详情查看:8月更文挑战

31. 栈的压入、弹出序列

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。

  • 示例 1:

输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1] 输出:true 解释:我们可以按以下顺序执行: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

  • 示例 2:

输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2] 输出:false 解释:1 不能在 2 之前弹出。

解题思路

  1. 将pushed数组里面的元素逐个压入栈,判断栈顶元素和popped数组是否相同,相同则出栈并且popped数组的指针后移
  2. 最后如果popped数组的指针指向了popped.length,说明出栈序列构造成功

代码

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {

        Stack<Integer> stack=new Stack<>();
        int cur=0;
        for (int i : pushed) {
            stack.push(i);
            while (cur<popped.length&&!stack.isEmpty()&&popped[cur]==stack.peek())
            {
                stack.pop();
                cur++;
            }
        }
        return cur==popped.length;

    }
}

剑指 Offer 32 - III. 从上到下打印二叉树 III

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

例如: 给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

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

提示:

节点总数 <= 1000

解题思路

  1. 使用队列实现BFS,完成二叉树的层序遍历
  2. 每一层的元素加入结果的列表的时候,从列表头或者列表尾加入,交替进行就可以实现之字形顺序遍历

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {


        LinkedList<TreeNode> nodes = new LinkedList<>();
        List<List<Integer>> res=new ArrayList<>();
        if(root==null) return res;
        nodes.add(root);
        boolean pos=true;
        while (!nodes.isEmpty())
        {
            int size=nodes.size();
            ArrayList<Integer> temp = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode cur = nodes.removeFirst();
                if (pos)
                temp.add(cur.val);
                else
                    temp.add(0,cur.val);
                if (cur.left!=null) nodes.add(cur.left);
                if (cur.right!=null) nodes.add(cur.right);
            }
            pos=!pos;
            res.add(temp);
        }
        return res;

    }
}