class Solution {
public int search(int[] nums, int target) {
if(nums.length==0)return -1;
int l=0,r=nums.length-1;
while(l<=r){
int mid=l+r>>1;
if(nums[mid]==target){
return mid;
}else if(nums[mid]<target){
l=mid+1;
}else{
r=mid-1;
}
}
return -1;
}
}
class Solution {
//双指针算法
public int removeElement(int[] nums, int val) {
int i=0;//标记目前位置
for(int j=0;j<nums.length;j++){
if(nums[j]!=val){
nums[i]=nums[j];
i++;
}
}
return i;
}
}
class Solution {
public int[] sortedSquares(int[] nums) {
int n=nums.length;
int[] ans=new int[n];
int k=n-1;
int i=0,j=nums.length-1;
//类似于归并排序
while(i<=j){
if(nums[i]*nums[i]<nums[j]*nums[j]){
ans[k--]=nums[j]*nums[j];
j--;
}else{
ans[k--]=nums[i]*nums[i];
i++;
}
}
return ans;
}
}
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int minlen=0x3f3f3f3f;
int sum=0;
int j=0;
for(int i=0;i<nums.length;i++){
sum+=nums[i];
while(sum>=target){//缩小区间
minlen=Math.min(minlen,i-j+1);
sum-=nums[j];
j++;//
}
}
if(minlen==0x3f3f3f3f)return 0;
return minlen;
}
}
class Solution {
static boolean[][] st;
public int[][] generateMatrix(int n) {
st=new boolean[n][n];
int[] dx={0,1,0,-1},dy={1,0,-1,0};
int[][] ans=new int[n][n];
int x=0,y=0,d=0;//横,纵坐标,转向指针
for(int i=1;i<=n*n;i++){
ans[x][y]=i;
st[x][y]=true;
int a=x+dx[d],b=y+dy[d];
if(a<0 || a>=n || b<0 || b>=n || st[a][b]){
d=(d+1)%4;
a=x+dx[d];
b=y+dy[d];
}
x=a;
y=b;
}
return ans;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null)return null;
ListNode dummy=new ListNode(-1);
dummy.next=head;
ListNode cur=dummy;
while(cur.next!=null){
if(cur.next.val==val){
cur.next=cur.next.next;
}else cur=cur.next;
}
return dummy.next;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre=null;
ListNode cur=head;
while(cur!=null){
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy=new ListNode(-1);
dummy.next=head;
ListNode cur=dummy;
while(cur.next!=null && cur.next.next!=null){
ListNode a=cur.next;
ListNode b=cur.next.next;
cur.next=b;
a.next=b.next;
b.next=a;
cur=a;
}
return dummy.next;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy=new ListNode(-1);
dummy.next=head;
ListNode cur=head;
int cnt=0;
while(cur!=null){
cnt++;
cur=cur.next;
}
cur=dummy;
cnt=cnt-n;
while(cnt-->0)cur=cur.next;
cur.next=cur.next.next;
return dummy.next;
}
}
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow=hasCycle(head);
if(slow==null)return null;
else{
ListNode fast=head;
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
}
return slow;
}
public static ListNode hasCycle(ListNode head){
ListNode slow=head;
ListNode fast=head;
while(fast!=null && fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow)return slow;
}
return null;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null || headB==null)return null;
int lenA=len(headA);
int lenB=len(headB);
ListNode curA=headA;
ListNode curB=headB;
if(lenA>lenB){
int t=lenA-lenB;
for(int i=0;i<t;i++){
curA=curA.next;
}
while(curA!=null && curA!=curB){
curA=curA.next;
curB=curB.next;
}
return curA;
}else{
int t=lenB-lenA;
for(int i=0;i<t;i++){
curB=curB.next;
}
while(curA!=null && curA!=curB){
curA=curA.next;
curB=curB.next;
}
return curA;
}
}
public static int len(ListNode head){
int cnt=0;
ListNode cur=head;
while(cur!=null){
cnt++;
cur=cur.next;
}
return cnt;
}
}
class Solution {
//可以进一步优化,一个+一个- 判断是否为0
public boolean isAnagram(String s, String t) {
int[] cnts=help(s);
int[] cntt=help(t);
for(int i=0;i<26;i++){
if(cnts[i]!=cntt[i])return false;
}
return true;
}
//字符统计
public static int[] help(String str){
char[] ch=str.toCharArray();
int[] cnt=new int[26];
for(int i=0;i<ch.length;i++){
cnt[ch[i]-'a']++;
}
return cnt;
}
}
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
ArrayList<Integer> ans=new ArrayList<>();
boolean[] st=new boolean[1010];
for(int num:nums1){
st[num]=true;
}
for(int num:nums2){
if(st[num]){
ans.add(num);
st[num]=false;
}
}
int[] res=new int[ans.size()];
for(int i=0;i<ans.size();i++){
res[i]=ans.get(i);
}
return res;
}
}
class Solution {
//双指针或者统计出现过的数
public boolean isHappy(int n) {
Set<Integer> set=new HashSet<>();
while(n!=1 && !set.contains(n)){
set.add(n);
// System.out.println(n);
n=get(n);
}
return n==1;
}
public static int get(int x){
int res=0;
while(x!=0){
int t=x%10;
res+=t*t;
x/=10;
}
return res;
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i]) )return new int[]{map.get(target-nums[i]),i};
map.put(nums[i],i);
}
return new int[]{-1,-1};
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i]) )return new int[]{map.get(target-nums[i]),i};
map.put(nums[i],i);
}
return new int[]{-1,-1};
}
}
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
HashMap<Integer,Integer> map=new HashMap<>();
int res=0;
int n=nums1.length;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
int t=nums1[i]+nums2[j];
map.put(-t,map.getOrDefault(-t,0)+1);
}
}
//优化得到On^2
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
int num=nums3[i]+nums4[j];
if(map.containsKey(num))res+=map.get(num);
}
}
return res;
}
}
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] cnt=new int[26];
char[] chm=magazine.toCharArray();
for(char c:chm){
cnt[c-'a']++;
}
char[] chr=ransomNote.toCharArray();
for(char c:chr){
cnt[c-'a']--;
}
for(int i=0;i<26;i++){
if(cnt[i]<0)return false;
}
return true;
}
}
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> ans=new ArrayList<>();
for(int i=0;i<nums.length-1;i++){
//排序之后如果第一个元素大于0,则无论任何组合都不能符合要求
if(nums[i]>0)return ans;
if( i>0 && nums[i]==nums[i-1])continue;//对第一个数进行去重
//针对[i+1,n-1]我们可以使用双指针算法
int j=i+1,k=nums.length-1;
while(j<k){
int sum=nums[i]+nums[j]+nums[k];
if(sum>0){
k--;
}else if(sum<0){
j++;
}else{
//符合要求后我们将加入答案
ans.add(Arrays.asList(nums[i],nums[j],nums[k]));
while(j<k && nums[j]==nums[j+1])j++;
while(j<k && nums[k]==nums[k-1])k--;
k--;
j++;
}
}
}
//对i的去重
return ans;
}
}
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
// target=(long)target;
List<List<Integer>> ans=new ArrayList<>();
Arrays.sort(nums);
int n=nums.length;
for(int i=0;i<n-3;i++){
if(i>0 && nums[i]==nums[i-1])continue;
if(nums[i]>0 && nums[i]>target)return ans;
for(int j=i+1;j<n-2;j++){
if(j>i+1&& nums[j]==nums[j-1])continue;
int l=j+1,r=n-1;
while(l<r){
long sum=(long)(nums[i]+nums[j]+nums[l]+nums[r]);
if(sum>Integer.MAX_VALUE)continue;
if(sum>target){
r--;
}else if(sum<target){
l++;
}else if(sum==target){
ans.add(Arrays.asList(nums[i],nums[j],nums[l],nums[r]));
while(l<r && nums[r]==nums[r-1]){
r--;
}
while(l<r && nums[l]==nums[l+1]){
l++;
}
l++;
r--;
}
}
}
}
return ans;
}
}
class Solution {
public void reverseString(char[] s) {
int i=0,j=s.length-1;
char tmp='a';
while(i<j){
tmp=s[i];
s[i]=s[j];
s[j]=tmp;
i++;
j--;
}
}
}
class Solution {
public String reverseStr(String s, int k) {
char[] ch=s.toCharArray();
int n=ch.length;
int tmp=n/(2*k);
for(int i=0;i<tmp;i++){
int l=0+i*2*k;
int r=l+k-1;
while(l<r){
char t=ch[l];
ch[l]=ch[r];
ch[r]=t;
l++;
r--;
}
}
// System.out.println(n%(2*k));
int l=tmp*2*k;
int r=n-1;
if(n%(2*k)>=k){
l=0+tmp*2*k;
r=l+k-1;
}
while(l<r){
char t=ch[l];
ch[l]=ch[r];
ch[r]=t;
l++;
r--;
}
return new String(ch);
}
}
class Solution {
public String replaceSpace(String s) {
StringBuilder sb=new StringBuilder();
for(int i=0;i<s.length();i++){
if(s.charAt(i)==' '){
sb.append("%20");
}else{
sb.append(s.charAt(i));
}
}
return new String(sb);
}
}
class Solution {
public String reverseWords(String s) {
if(s.length()==0)return "";
int i=0,j=s.length()-1;
while(i<s.length() && s.charAt(i)==' ')i++;
while(j>=0 && s.charAt(j)==' ')j--;
if(i>j)return "";
StringBuilder sb=new StringBuilder();
//直接使用StringBuilder进行遍历,去除空格
while(i<=j){
char c=s.charAt(i);
//这里第二个条件十分巧妙,当有连续两个空格是,只会加第一个
if(c!=' ' || sb.charAt(sb.length()-1)!=' ')sb.append(c);
i++;
}
//反转整个字符串
reverse(sb,0,sb.length()-1);
//反转单个单词
i=0;
while(i<sb.length()){
j=i;
while(j<sb.length() && sb.charAt(j)!=' ')j++;
reverse(sb,i,j-1);
i=j+1;
}
return sb.toString();
}
//反转指定区间的字符串[]
public StringBuilder reverse(StringBuilder sb,int l,int r){
while(l<r){
char t=sb.charAt(l);
sb.setCharAt(l,sb.charAt(r));
sb.setCharAt(r,t);
l++;
r--;
}
return sb;
}
}
思路解析
if(c!=' ' || sb.charAt(sb.length()-1)!=' ')sb.append(c);
:第二个条件确保我们可以单词间只加一个空格,值得注意
整体思路在于:去空,先将整个单词反转,而后逐个反转每个单词
- 该方法尽管只是O(n)级别的复杂度,但是需要扫描两边,我们接下来看一中只需要扫描一遍的做法
class Solution {
//代码整体更加简洁
public String reverseWords(String s) {
char[] sc=s.toCharArray();
StringBuilder sb=new StringBuilder();
//去除首尾空格
int left=0,right=sc.length-1;
while(sc[left]==' ')left++;
while(sc[right]==' ')right--;
//right永远指向当前单词的最后一个位置,
//index+1:用来搜寻,当前单词的第一个位置(index定位到空格)
while(left<=right){
//倒着扫描
int index=right;
//确定最后一个单词的起始位置
while(index>=left && sc[index]!=' ')index--;
for(int i=index+1;i<=right;i++){
sb.append(sc[i]);
}
//如果不是第一个单词,后面加一个空格
if(index>left)sb.append(' ');
//指针移动至下一个单词的末尾
while(index>=left && sc[index]==' ')index--;
right=index;
}
return sb.toString();
}
}
class Solution {
public String reverseLeftWords(String s, int n) {
char[] ch=s.toCharArray();
StringBuilder sb=new StringBuilder();
for(int i=0;i<ch.length;i++){
sb.append(ch[(n)%ch.length]);
n=n+1;
}
return sb.toString();
}
}
思路分析
class Solution {
//KMP算法
static int[] next;
public int strStr(String haystack, String needle) {
int n=haystack.length();
int m=needle.length();
char[] ch=(" "+haystack).toCharArray();
char[] cn=(" "+needle).toCharArray();
next=new int[cn.length];
next(cn);
for(int i=1,j=0;i<=n;i++){
while(j!=0 && ch[i]!=cn[j+1])j=next[j];
if(ch[i]==cn[j+1])j++;
if(j==m)return (i-m);
}
return -1;
}
public static void next(char[] ch){
int n=ch.length;
//next[1]指定为0
for(int i=2,j=0;i<n;i++){
while(j!=0 && ch[i]!=ch[j+1])j=next[j];
if(ch[i]==ch[j+1])j++;
next[i]=j;
}
}
}
class Solution {
public boolean repeatedSubstringPattern(String s) {
int n=s.length();
char[] ch=(" "+s).toCharArray();
int[] ne=new int[n+1];
for(int i=2,j=0;i<=n;i++){
while(j!=0 && ch[i]!=ch[j+1])j=ne[j];
if(ch[i]==ch[j+1])j++;
ne[i]=j;
}
int t=n-ne[n];
return (t<n && n%t==0);
}
}
class Solution {
public int removeElement(int[] nums, int val) {
//一个指针指向当前位置,一个指向需要更换的位置
int n=nums.length;
int i=0,j=0;
while(j<n){
while(j<n && nums[j]==val)j++;
// System.out.println(i+" "+j);
if(j>=n)break;
int t=nums[i];
nums[i]=nums[j];
nums[j]=t;
j++;
i++;
}
return i;
}
}
class Solution {
public void reverseString(char[] s) {
int i=0,j=s.length-1;
while(i<j){
char t=s[i];
s[i]=s[j];
s[j]=t;
i++;
j--;
}
// return s;
}
}
class Solution {
public String reverseWords(String s) {
char[] ch=s.toCharArray();
int l=0,r=s.length()-1;
//去除首尾空格
while(ch[l]==' ')l++;
while(ch[r]==' ')r--;
//倒着扫描
StringBuilder sb=new StringBuilder();
while(l<=r){
int i=r;
while(i>=l && ch[i]!=' ')i--;
for(int j=i+1;j<=r;j++)sb.append(ch[j]);
if(i>l)sb.append(" ");
//指针移动
r=i;
//移到下一个单词末尾
while(r>=l && ch[r]==' ')r--;
}
return new String(sb);
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre=null;
ListNode cur=head;
while(cur!=null){
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
//快慢指针
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy=new ListNode(-1);
dummy.next=head;
ListNode fast=dummy;
ListNode slow=dummy;
for(int i=0;i<=n;i++)fast=fast.next;
while(fast!=null){
slow=slow.next;
fast=fast.next;
}
slow.next=slow.next.next;
return dummy.next;
}
}
class MyQueue {
static ArrayDeque<Integer> sta;
static ArrayDeque<Integer> h;
public MyQueue() {
sta=new ArrayDeque<>();
h=new ArrayDeque<>();
}
public void push(int x) {
sta.push(x);
}
public int pop() {
if(!h.isEmpty()){
return h.pop();
}else{
while(!sta.isEmpty()){
h.push(sta.pop());
}
}
return h.pop();
}
public int peek() {
if(!h.isEmpty()){
return h.peek();
}else{
while(!sta.isEmpty()){
h.push(sta.pop());
}
}
return h.peek();
}
public boolean empty() {
return sta.isEmpty()&&h.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
class MyStack {
ArrayDeque<Integer> q;
public MyStack() {
q=new ArrayDeque<>();
}
public void push(int x) {
q.offer(x);
int size=q.size();
size--;
while(size-->0){
q.offer(q.poll());
}
}
public int pop() {
return q.poll();
}
public int top() {
return q.peek();
}
public boolean empty() {
return q.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
class Solution {
public int evalRPN(String[] tokens) {
ArrayDeque<Integer> sta=new ArrayDeque<>();
for(int i=0;i<tokens.length;i++){
if(isNumeric(tokens[i]))sta.push(Integer.parseInt(tokens[i]));
else{
int b=sta.pop();
int a=sta.pop();
sta.push(cal(a,b,tokens[i]));
}
}
return sta.pop();
}
public int cal(int a,int b,String m){
if(m.equals("+"))return a+b;
if(m.equals("-"))return a-b;
if(m.equals("*"))return a*b;
if(m.equals("/"))return a/b;
return 0;
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?"); // 使用正则表达式判断是否为数字
}
}
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int n=nums.length;
int m=0;
int[] ans=new int[n-k+1];
ArrayDeque<Integer> q=new ArrayDeque<>();
for(int i=0;i<nums.length;i++){
if(!q.isEmpty() && i-q.peek()>=k)q.poll();
while(!q.isEmpty()&& nums[i]>=nums[q.peekLast()]){
// if(i==3)System.out.println(nums[q.peek()]);
q.pollLast();
}
q.offer(i);
if(i>=k-1){
ans[m++]=nums[q.peek()];
}
}
return ans;
}
}
class Solution {
public int[] topKFrequent(int[] nums, int k) {
PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> o1[1] - o2[1]);
Map<Integer,Integer> map=new HashMap<>();
for(int num:nums)map.put(num,map.getOrDefault(num,0)+1);
for(var x:map.entrySet()){
int[] tmp=new int[2];
tmp[0]=x.getKey();
tmp[1]=x.getValue();
pq.add(tmp);
}
while(pq.size()>k)pq.poll();
int[] ans=new int[k];
for(int i=0;i<k;i++){
ans[i]=pq.poll()[0];
}
return ans;
}
}
前序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
pre(res,root);
return res;
}
static void pre(List<Integer> res,TreeNode root){
if(root==null)return;
res.add(root.val);
pre(res,root.left);
pre(res,root.right);
}
}
后序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
//迭代解决
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans=new ArrayList<>();
posOrder(root,ans);
return ans;
}
private void posOrder(TreeNode root,List<Integer> ans){
if(root==null){
return;
}
posOrder(root.left,ans);
posOrder(root.right,ans);
ans.add(root.val);
}
}
中序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
in(root,res);
return res;
}
static void in(TreeNode root,List<Integer> res){
if(root==null)return;
in(root.left,res);
res.add(root.val);
in(root.right,res);
}
}
前序遍历
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
if(root==null)return res;
ArrayDeque<TreeNode> sta=new ArrayDeque<>();
sta.push(root);
while(!sta.isEmpty()){
TreeNode t=sta.pop();
res.add(t.val);
if(t.right!=null)sta.push(t.right);
if(t.left!=null)sta.push(t.left);
}
return res;
}
}
后序遍历
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
if(root==null)return res;
ArrayDeque<TreeNode> sta=new ArrayDeque<>();
sta.push(root);
while(!sta.isEmpty()){
TreeNode t=sta.pop();
res.add(0,t.val);
//因为我们要进行反转,所以先入左节点,后右节点,弹出(右左),反转(左右)
if(t.left!=null)sta.push(t.left);
if(t.right!=null)sta.push(t.right);
}
return res;
}
}
中序遍历
Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
ArrayDeque<TreeNode> sta=new ArrayDeque<>();
while(root!=null || !sta.isEmpty()){
while(root!=null){//只要结点的左子树不空,就向左遍历
sta.push(root);
root=root.left;
}
if(!sta.isEmpty()){//将所有的左子树节点加入之后我们进行遍历
root=sta.pop();//将当前栈顶元素弹出
res.add(root.val);//遍历该元素
root=root.right;//遍历该元素的右子树
}
}
return res;
}
}
/**
class Solution {
public List> levelOrder(TreeNode root) {
List> ans=new ArrayList<>();
if(root==null)return ans;
ArrayDeque q=new ArrayDeque<>();
q.offer(root);
while(!q.isEmpty()){
int size=q.size();
List level=new ArrayList<>();
for(int i=0;i
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> ans=new ArrayList<>();
if(root==null)return ans;
ArrayDeque<TreeNode> q=new ArrayDeque<>();
q.offer(root);
while(!q.isEmpty()){
int size=q.size();
List<Integer> level=new ArrayList<>();
for(int i=0;i<size;i++){
TreeNode t=q.poll();
level.add(t.val);
if(t.left!=null)q.offer(t.left);
if(t.right!=null)q.offer(t.right);
}
ans.add(0,level);
}
return ans;
}
}
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> ans=new ArrayList<>();
ArrayDeque<TreeNode> q=new ArrayDeque<>();
if(root==null)return ans;
q.offer(root);
while(!q.isEmpty()){
int size=q.size();
for(int i=0;i<size;i++){
TreeNode t=q.poll();
if(i==size-1)ans.add(t.val);
if(t.left!=null)q.offer(t.left);
if(t.right!=null)q.offer(t.right);
}
}
return ans;
}
}
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> ans=new ArrayList<>();
ArrayDeque<TreeNode> q=new ArrayDeque<>();
if(root==null)return ans;
q.offer(root);
while(!q.isEmpty()){
int size=q.size();
double sum=0;
for(int i=0;i<size;i++){
TreeNode t=q.poll();
sum+=(double)t.val;
if(t.left!=null)q.offer(t.left);
if(t.right!=null)q.offer(t.right);
if(i==size-1)ans.add(sum/(double)size);
}
}
return ans;
}
}
/*
// Definition for a Node.
class Node {
public int val;
public List children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> ans=new ArrayList<>();
ArrayDeque<Node> q=new ArrayDeque<>();
if(root==null)return ans;
q.offer(root);
while(!q.isEmpty()){
int size=q.size();
List<Integer> level=new ArrayList<>();
for(int i=0;i<size;i++){
Node t=q.poll();
level.add(t.val);
for(Node node:t.children){
if(node!=null)q.offer(node);
}
}
ans.add(level);
}
return ans;
}
}