完全二叉树的节点数(用两种逻辑来计算,一个是满,一个是普通
观察左右子树的高度是否相等,再分为两种模式来算
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();
}
}