/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/classSolution{
int a =0;int val =0;public boolean isUnivalTree(TreeNode root){
if(a ==0){
val = root.val;}
a++;if(root ==null){
returntrue;}if(root.val != val){
returnfalse;}returnisUnivalTree(root.left)&&isUnivalTree(root.right);}}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/classSolution{
public boolean isUnivalTree(TreeNode root){
boolean flag =true;if(root ==null){
returntrue;}
flag =isUnivalTree(root.left);
flag &=isUnivalTree(root.right);if((root.left!=null&& root.left.val!=root.val)||(root.right!=null&& root.right.val!=root.val)){
flag =false;}return flag;}}
力扣617 合并二叉树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/classSolution{
publicTreeNodemergeTrees(TreeNode t1,TreeNode t2){
if(t1 ==null){
return t2;}if(t2 ==null){
return t1;}TreeNode merge =newTreeNode(t1.val + t2.val);
merge.left =mergeTrees(t1.left, t2.left);
merge.right =mergeTrees(t1.right, t2.right);return merge;}}
力扣167 两数之和2
classSolution{
publicint[]twoSum(int[] numbers,int target){
int len = numbers.length;int k2 = len-1;int k1 =0;int[] result =newint[2];while(k1<k2){
if(numbers[k1]+numbers[k2]==target){
result[0]= k1+1;
result[1]= k2+1;return result;}if(numbers[k1]+numbers[k2]>target){
k2--;}else{
k1++;}}return result;}}
剑指offer11 旋转数组的最小数字
classSolution{
publicintminArray(int[] numbers){
int result = numbers[0];for(int i=1; i<numbers.length; i++){
if(numbers[i]<numbers[i-1]){
return numbers[i];}}return result;}}
剑指offer09 用两个栈实现队列
思路:用两个栈 栈1用来增加元素,stack1.push即可
栈2用来删除元素,首先,当栈2不为空时,直接pop()
当栈2为空时,将刚刚增加的元素(栈1中的元素依次入栈,可能是多个,可以理解为栈1是栈2的仓库,没有了就来拿),当栈2仍然为空时(栈1也是空的,栈2也是空的),返回-1。
classCQueue{
Stack<Integer> stack1 =newStack<Integer>();
Stack<Integer> stack2 =newStack<Integer>();publicCQueue(){
}publicvoidappendTail(int value){
stack1.push(value);}publicintdeleteHead(){
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());}}if(stack2.isEmpty()){
return-1;}else{
int head = stack2.pop();return head;}}}/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/