1.二叉树的中序遍历
方法一:递归实现
res,存储返回结果
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res =new ArrayList<>(); inorder(root, res); return res; } public static void inorder(TreeNode treeNode,List<Integer> res){ if (treeNode==null) return ; inorder(treeNode.left,res); res.add(treeNode.val); inorder(treeNode.right,res); } }
方法二:迭代实现
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res =new ArrayList<Integer>(); Deque<TreeNode> stk =new LinkedList<TreeNode>(); //栈 存储来时的路,后进先出 while (root!=null || !stk.isEmpty()) { if (root!=null) { stk.push(root);//存储来时的路 root=root.left; }else{ TreeNode temp=stk.pop();//出栈 res.add(temp.val);//打印出栈的值(前) root=temp.right;//处理遍历右子树 } } return res; } }
方法三:前中后序遍历迭代统一实现
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res =new ArrayList<Integer>(); Deque<TreeNode> stk =new LinkedList<TreeNode>(); //栈 存储来时的路,后进先出 TreeNode pop=null; while (root!=null || !stk.isEmpty()) { if (root!=null) { stk.push(root); root=root.left;//处理(遍历)左子树 }else{//与第一种迭代方法不同,不直接出栈栈顶元素 //而是先判断是否有右子树,无右子树,再出栈 TreeNode peek =stk.peek();//保存栈顶元素 if (peek.right==null) {//无右子树 res.add(peek.val); pop=stk.pop();//出栈 } //右子树处理完成 else if (peek.right==pop) { pop=stk.pop();//出栈 } //待处理(遍历)右子树 else{ res.add(peek.val); root=peek.right;//处理右子树 } } } return res; } }
2. 二叉树的最大深度
树的深度=最大的节点度+1---迭代方法找节点的度
class Solution {
public int maxDepth(TreeNode root) {
if (root==null) {
return 0;//终止条件
}
int maxLeft=maxDepth(root.left);
int maxRight=maxDepth(root.right);
return Math.max(maxLeft,maxRight )+1;
}
}
3.翻转二叉树
左子树变右子树,右子树变左子树
方法一:递归
目标:左子树变右子树,右子树变左子树
我们从根节点开始,递归地对树进行遍历,并从叶子节点先开始翻转。如果当前遍历到的节点 root 的左右两棵子树都已经翻转,那么我们只需要交换两棵子树的位置,即可完成以root 为根节点的整棵子树的翻转。
class Solution { public TreeNode invertTree(TreeNode root) { if (root==null) { return null; } TreeNode left=invertTree(root.left); TreeNode right=invertTree(root.right); root.left=right; root.right=left; return root; } }
4.对称二叉树
方法一:递归实现
递归的比较左子树和右子树
从根节点root开始,比较其左节点与又节点是否相等
再递归比较 左节点的左节点 与 右节点的右节点
左节点的右节点 与 右节点的左节点
递归头: 终止条件
(1)左右节点的值不同;(2)左节点或右节点为null
class Solution { public boolean isSymmetric(TreeNode root) { if (root == null) return true; return dfs(root.left, root.right); } public boolean dfs(TreeNode left, TreeNode right){ //返回true 的判断 if (left==null && right==null) return true; //返回false的判断 //递归头:左或右节点为空,左右节点值不同 if (left==null || right==null) return false; if (left.val!=right.val) return false; //递归比较左左右右,左右右左节点 return dfs(left.left, right.right) && dfs(left.right, right.left); } }
方法二:迭代实现+队列(先进先出)
class Solution { public boolean isSymmetric(TreeNode root) { if (root == null) return true; //存储左右子树,用以比较 Deque<TreeNode> deque=new LinkedList<TreeNode>(); deque.add(root.left); deque.add(root.right); while (!deque.isEmpty()) { TreeNode left=deque.remove(); TreeNode right=deque.remove(); //某个节点的左右子树判断结束,继续判断 //直到队列为空 if (left==null && right==null) continue; //提前结束 if (left==null || right==null) return false; if (left.val!= right.val) return false; //队列中添加左左子树等 deque.add(left.left); deque.add(right.right); deque.add(left.right); deque.add(right.left); } return true; } }
5.二叉树的直径--DFS
4--2--1--3
深度优先搜素--递归
二叉树的直径==Max(所有节点 [(左子树深度)+(右子树深度)]+1)
递归找每个节点的深度
用变量ans保存 之前节点深度的最大值 与当前的节点深度
class Solution {
int ans =0;
public int diameterOfBinaryTree(TreeNode root) {
if (root==null) return 0;
dfs(root);//递归找每个节点的深度
return ans;//保存的每个节点的左右深度
}
public int dfs(TreeNode root){
if (root==null) return 0;//空节点深度为0
int maxLeft=dfs(root.left); //左儿子为根的子树的深度
int maxRight=dfs(root.right);// 右儿子为根的子树的深度
int preMax=maxLeft+maxRight;//这里不加1
// L+R+1
ans=Math.max(ans, preMax);
return Math.max(maxLeft, maxRight)+1;// 返回该节点为根的子树的深度
}
}
6.二叉树的层序遍历--BFS
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
Deque<TreeNode> deque =new LinkedList<TreeNode>();
if(root!=null) deque.add(root);
while (!deque.isEmpty()) {
LinkedList<Integer> temp =new LinkedList<Integer>();
for (int i=deque.size();i>0;i--) {
TreeNode remove=deque.remove();
temp.add(remove.val);
if (remove.left!=null) deque.add(remove.left);
if (remove.right!=null) deque.add(remove.right);
}
res.add(temp);
}
return res;
}
}
7.将有序数组转换为二叉搜索树
BST 的中序遍历是升序的,因此本题等同于根据中序遍历的序列恢复二叉搜索树。
可以以升序序列中的任一个元素作为根节点,
以该元素左边的升序序列构建左子树,以该元素右边的升序序列构建右子树(递归构建树)
这样得到的树就是一棵二叉搜索树
本题要求高度平衡,因此我们需要选择升序序列的中间元素作为根节点
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return df(nums, 0, nums.length-1);
}
public TreeNode df (int[] nums, int low,int hight){
if (low>hight) return null;//空树
int mid=low+(hight-low)/2;
TreeNode root =new TreeNode(nums[mid]);//根节点
//以nums[mid]左边的升序序列构建左子树--递归
//同理构建右子树
root.left=df(nums, low, mid-1);
root.right=df(nums, mid+1, hight);
return root;
}
}
扩展:有序链表转二叉搜索树--找中间值
8.验证二叉搜索树
左子树的所有节点的值 < 根节点值 < 右子树的所有的节点的值
递归验证每个节点的左节点小于当前节点,右节点大于当前节点 ,
终止条件:root走到null,空树直接返回true
还要限制左右节点的范围
class Solution { public boolean isValidBST(TreeNode root) { if (root==null) return false ;//空树 return df(root,null,null); } public boolean df(TreeNode root,TreeNode min,TreeNode max) { //走到null 终止条件 if (root == null) return true; //验证 if(min!=null && min.val>=root.val) return false; if(max!=null && max.val<=root.val) return false; return df(root.left, min,root)&&df(root.right,root,max); } }
9.二叉搜索树中第K小的元素
迭代(root=root.left)+栈
一直root.left走到null--走到最左点(倒数第1小),并将来时的路存储到栈中
出栈:出栈一个,k--,如果k==0,结束(第k小在左子树上)
否则:向右走一个节点
然后重复上述一直往左走
往回走k-1步,弹出的第k个元素即为第k小
class Solution {
public int kthSmallest(TreeNode root, int k) {
//存储向左走来时的路
Deque<TreeNode> stk=new LinkedList<TreeNode>();
TreeNode pop=null;
while (root!=null||!stk.isEmpty()) {
//存 根节点 开始一直向左走的路
while (root!=null) {
stk.push(root);
root=root.left;
}
root=stk.pop();//处理右子树前,root保存树的原始根节点
--k;
if (k==0) {break;}
root=root.right; //左子树都处理完了,向右走
}
return root.val;
}
}
10.二叉树的右视图
class Solution {
List<Integer> ans=new ArrayList<Integer>();
public List<Integer> rightSideView(TreeNode root) {
df(root, 0);
return ans;
}
public void df(TreeNode root,int depth){
//终止条件
if(root==null) return;
if(depth==ans.size()) ans.add(root.val);
df(root.right, depth+1);//下一个节点的深度为上一个节点的+1
df(root.right, depth+1);
}
}
11. 二叉树展开为链表
其实是分为三步:
首先将根节点的左子树变成链表
其次将根节点的右子树变成链表
最后将变成链表的右子树放在变成链表的左子树的最右边
这就是一个递归的过程,递归的一个非常重要的点就是:不去管函数的内部细节是如何处理的,我们只看其函数作用以及输入与输出。对于函数flatten来说:
函数作用:将一个二叉树,原地将它展开为链表
输入:树的根节点
输出:无
那我们就直接根据三步来写程序就可以了
class Solution {
public void flatten(TreeNode root) {
if(root==null) return ;
flatten(root.left);
flatten(root.right); // 第一二步,将左右子树转为链表
//第三步左挂右(清空左), 右挂右(找最右节点)
TreeNode temp = root.right;
root.right=root.left;
root.left=null;
while(root.right!=null) root=root.right;
root.right=temp;
}
}
12.105. 从前序与中序遍历序列构造二叉树
class Solution {
HashMap<Integer,Integer> map=new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
int n=preorder.length;
for (int i = 0; i < n; i++) {
map.put(inorder[i], i);
}
return df(preorder, inorder, 0, n-1, 0, n-1);
}
public TreeNode df(int[] preorder, int[] inorder,int PL, int PR,int IL,int IR){
if(PL>PR) return null;
int P_root=PL;
int I_root=map.get(preorder[P_root]); // 找到根节点在中序中的位置
TreeNode root=new TreeNode(preorder[P_root]);
//根据中序遍历构造左右子树
//确定前序遍历中左右子树的起始位置 -- 得到左子树中节点的个数
int L_size=I_root-IL;
root.left=df(preorder, inorder, PL+1, PL+L_size, IL, I_root-1);
root.right=df(preorder, inorder, PL+L_size+1, PR, I_root+1, IR);
return root;
}
}
13 路径总和3
方法一:穷举法
class Solution {
public int pathSum(TreeNode root, int targetSum) {
if(root==null) return 0;
int ans=nodeSum(root, (long)targetSum);// 该节点出发 符合要求的 路径数目
ans+=pathSum(root.left, targetSum); // 该节点子树的路径
ans+=pathSum(root.right, targetSum);
return ans;
}
//穷举每个节点出发符合的路径 的 数目
public int nodeSum(TreeNode root, Long targetSum){
if(root==null) return 0;
int temp=0;
if(root.val==targetSum) temp++;
temp+=nodeSum(root.left, targetSum-root.val);
temp+=nodeSum(root.right, targetSum-root.val);
return temp;
}
}
方法二:前缀和+哈希+回溯(当前节点结束,需回溯)
恢复状态码---回溯
回溯
//对应这个,非该节点的子节点,无法用此前缀和(该节点的前缀和)
class Solution {
HashMap<Long ,Integer> map;
//int ans;
public int pathSum(TreeNode root, int targetSum) {
map=new HashMap<>();
map.put(0L,1);
return df(root, targetSum,0);
}
//根节点root到当前节点node的前缀和 preSum
//返回值:当前节点为树 中 符号要求的 路径数目
public int df(TreeNode node, long targetSum,long preSum){
if(node==null) return 0;
int ans=0;
preSum+=node.val;
ans+=map.getOrDefault(preSum-targetSum, 0);
//对应这个,非该节点的子节点,无法用此前缀和
map.put(preSum, map.getOrDefault(preSum, 0)+1);
ans+=df(node.left, targetSum, preSum);
ans+=df(node.right, targetSum, preSum);
map.put(preSum, map.getOrDefault(preSum, 0)-1); // 重点 对应上面
return ans;
}
}
14. 236. 二叉树的最近公共祖先
递归函数逻辑:当前节点root能否找到 p , q节点
返回值含义:
class Solution {
//函数 在root节点是否能找到p,q节点
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root==null||root==p||root==q) {
return root;
}
TreeNode left=lowestCommonAncestor(root.left, p, q);
TreeNode right=lowestCommonAncestor(root.right, p, q);
if(left==null) return right;
if(right==null) return left;
return root;
}
}
同上
15.124. 二叉树中的最大路径和
class Solution {
int ans=Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
df(root);
return ans;
}
//函数, root及其左右子树的val值和 ;
//curSum:val值和
//返回值:一边的结果(只连左子树或右子树)
//子树小于0,不加在一起
public int df(TreeNode root){
if(root==null) return 0;
int curSum=0; //记录当前链的val值和
int left=Math.max(0, df(root.left));
int right=Math.max(0, df(root.right));
curSum=root.val+left+right;
ans=Math.max(ans, curSum);
return Math.max(root.val+Math.max(left, right), 0);// 只能要一边
}
}