完全二叉树、队列和栈(pop 栈 poll队列

完全二叉树的节点数(用两种逻辑来计算,一个是满,一个是普通

观察左右子树的高度是否相等,再分为两种模式来算

class Solution {
    public int countNodes(TreeNode root) {
        if(root==null) return 0;
        TreeNode l=root,r=root;//两个指针
        int lh=1,rh=1;
        while(l.left!=null){
            l=l.left;
            lh++;
        }
        while(r.right!=null){
            r=r.right;
            rh++;
        }
        if(lh==rh){
            return (int)Math.pow(2,lh)-1;
        }
        int left=countNodes(root.left);
        int right=countNodes(root.right);//如果不相等就计算左右子树
        return left+right+1;
    }
}

栈和队列

 if (s2.isEmpty())

class MyQueue {
    Stack<Integer> s1,s2;
    public MyQueue() {
        s1=new Stack();
        s2=new Stack();
    }
    
    public void push(int x) {
        s1.add(x);
    }
    
    public int pop() {
        if (s2.isEmpty()) {//关键代码
            while (!s1.isEmpty()) {
                s2.push(s1.pop());
            }
        }
        return s2.pop();
    }
    
    public int peek() {
        if (s2.isEmpty()) {
            while (!s1.isEmpty()) {
                s2.push(s1.pop());
            }
        }
        return s2.peek();
    }
    
    public boolean empty() {
        return s1.isEmpty()&&s2.isEmpty();
    }
}

两个队列模拟栈,q1存放之前的元素,q2存放后来的元素

class MyStack {
    Queue<Integer> q1,q2;
    public MyStack() {
        q1=new LinkedList<>();//用来维护栈的顺序
        q2=new LinkedList<>();//放新的
    }
    
    public void push(int x) {
        q2.add(x);
        while(!q1.isEmpty()){
            q2.add(q1.poll());
        }
        Queue<Integer> temp=q1;
        q1=q2;
        q2=temp;
    }
    
    public int pop() {
        return q1.poll();
    }
    
    public int top() {
        return q1.peek();
    }
    
    public boolean empty() {
        return q1.isEmpty();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值