码迷,mamicode.com
首页 > 编程语言 > 详细

Java--剑指offer(5)

时间:2016-08-20 19:07:54      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

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

import java.util.Stack;

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        Stack s = new Stack();
        int i = 0,j = 0;
        s.push(pushA[i++]);
        
        if(pushA == null || popA == null){
            return false;
        }else if(pushA.length == 0 || popA.length == 0){
            return false;
        }else if(pushA.length != popA.length){
            return false;
        }else{
            while(j <= popA.length - 1){
                while(popA[j] != s.peek()){
                    if(i == pushA.length){
                        return false;
                    }
                    s.push(pushA[i++]);
                }
                j++;
                s.pop();
            }
        }
        
        return true;
    }
}

 

22.从上往下打印出二叉树的每个节点,同层节点从左至右打印。

import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> treeList = new ArrayList<Integer>();
     //这里要注意的是,Queue是一个接口,不能直接创建Queue的实例,只能创建实现Queue接口的子类 Queue
<TreeNode> q = new LinkedList<TreeNode>(); q.offer(root); if(root == null){ return treeList; } while(!q.isEmpty()){ TreeNode temp = q.poll(); treeList.add(temp.val); if(temp.left != null) q.offer(temp.left); if(temp.right != null) q.offer(temp.right); } return treeList; } }

 

Java--剑指offer(5)

标签:

原文地址:http://www.cnblogs.com/wgl1995/p/5790866.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!