二叉树
BM23 二叉树的前序遍历
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
ArrayList<Integer> list=new ArrayList<>();
public int[] preorderTraversal (TreeNode root) {
pre(root);
int[] res=new int[list.size()];
for(int i=0;i<list.size();i++){
res[i]=list.get(i);
}
return res;
}
private void pre(TreeNode root){
if(root==null) return;
list.add(root.val);
pre(root.left);
pre(root.right);
}
}
// 先把当前节点的值保存到list中,然后再把它的右孩子节点、左孩子节点分别压入stack中
private void pre(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
if(root == null)return;
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
list.add(node.val);
if (node.right != null) stack.push(node.right);
if (node.left != null) stack.push(node.left);
}
}
BM24 二叉树的中序遍历
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
ArrayList<Integer> list=new ArrayList<>();
public int[] inorderTraversal (TreeNode root) {
in(root);
int[] res=new int[list.size()];
for(int i=0;i<list.size();i++){
res[i]=list.get(i);
}
return res;
}
private void in(TreeNode root){
if(root==null) return;
in(root.left);
list.add(root.val);
in(root.right);
}
}
//
private void in(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
if(root == null)return;
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.add(root);
root = root.left;
}
TreeNode node = stack.pop();
list.add(node.val);
root = node.right;
}
}
BM25 二叉树的后序遍历
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
ArrayList<Integer> list =new ArrayList<>();
public int[] postorderTraversal (TreeNode root) {
post(root);
int[] res=new int[list.size()];
for(int i=0;i<list.size();i++){
res[i]=list.get(i);
}
return res;
}
private void post(TreeNode root){
if(root==null) return;
post(root.left);
post(root.right);
list.add(root.val);
}
}
//
private void post(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
if(root == null) return;
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
list.add(node.val);
if (node.left != null) stack.push(node.left);
if (node.right != null) stack.push(node.right);
}
Collections.reverse(list);
}
BM26 求二叉树的层序遍历
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
ArrayList<ArrayList<Integer>> res=new ArrayList<>();
ArrayList<TreeNode> queue=new ArrayList<>();
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
if(root!=null) queue.add(root);
while(queue.size()!=0){
ArrayList<Integer> path=new ArrayList<>();
for(int i=queue.size()-1;i>=0;i--){
TreeNode node=queue.remove(0);
path.add(node.val);
if(node.left!=null) queue.add(node.left);
if(node.right!=null) queue.add(node.right);
}
res.add(path);
}
return res;
}
}
BM27 按之字形顺序打印二叉树
import java.util.ArrayList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer>> res=new ArrayList<>();
ArrayList<TreeNode> queue=new ArrayList<>();
public ArrayList<ArrayList<Integer> > Print(TreeNode root) {
if(root!=null) queue.add(root);
while(queue.size()!=0){
ArrayList<Integer> path=new ArrayList<>();
for(int i=queue.size()-1;i>=0;i--){
TreeNode node=queue.remove(0);
if(res.size()%2==1) path.add(0,node.val);
else path.add(node.val);
if(node.left!=null) queue.add(node.left);
if(node.right!=null) queue.add(node.right);
}
res.add(path);
}
return res;
}
}
BM28 二叉树的最大深度
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
public int maxDepth (TreeNode root) {
if(root==null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}
BM29 二叉树中和为某一值的路径(一)
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
public boolean hasPathSum (TreeNode root, int sum) {
if(root==null) return false;
sum=sum-root.val;
if(root.left==null && root.right==null && sum==0) return true;
return hasPathSum(root.left,sum) || hasPathSum(root.right,sum);
}
}
BM30 二叉搜索树与双向链表
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
TreeNode pre,head;
public TreeNode Convert(TreeNode root) {
if(root==null) return null;
in(root);
return head;
}
private void in(TreeNode cur){
if(cur==null) return;
in(cur.left);
if(pre==null) head=cur;
else pre.right=cur;
cur.left=pre;
pre=cur;
in(cur.right);
}
}
BM31 对称的二叉树
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
boolean isSymmetrical(TreeNode root) {
if(root==null) return true;
return dfs(root.left,root.right);
}
private boolean dfs(TreeNode l,TreeNode r){
if(l==null && r==null) return true;
if(l==null || r==null || l.val!=r.val) return false;
return dfs(l.left,r.right) && dfs(l.right,r.left);
}
}
BM32 合并二叉树
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1==null||root2==null) return root1==null?root2:root1;
return dfs(root1,root2);
}
public TreeNode dfs(TreeNode r1,TreeNode r2){
if(r1==null||r2==null) return r1==null?r2:r1;
r1.val+=r2.val;
r1.left=dfs(r1.left,r2.left);
r1.right=dfs(r1.right,r2.right);
return r1;
}
}
BM33 二叉树的镜像
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public TreeNode Mirror (TreeNode root) {
if(root==null) return null;
TreeNode tmp=root.left;
root.left=Mirror(root.right);
root.right=Mirror(tmp);
return root;
}
}
BM34 判断是不是二叉搜索树
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
long pre=Long.MIN_VALUE;
public boolean isValidBST (TreeNode root) {
if(root==null) return true;
if(!isValidBST(root.left)) return false;
if(root.val<=pre) return false;
pre=root.val;
return isValidBST(root.right);
}
}
BM35 判断是不是完全二叉树
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
int n=0,p=0;;
public boolean isCompleteTree (TreeNode root) {
if(root==null) return true;
dfs(root,1);
return n==p;
}
private void dfs(TreeNode root,int i){
if(root==null) return;
n++;
p=Math.max(p,i);
dfs(root.left,2*i);
dfs(root.right,2*i+1);
}
}
BM36 判断是不是平衡二叉树
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null) return true;
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right)
&& Math.abs(depth(root.left)-depth(root.right))<=1;
}
private int depth(TreeNode root){
if(root==null) return 0;
return Math.max(depth(root.left),depth(root.right))+1;
}
}
BM37 二叉搜索树的最近公共祖先
import java.util.*;
public class Solution {
public int lowestCommonAncestor (TreeNode root, int p, int q) {
if(root.val>p && root.val>q) return lowestCommonAncestor(root.left,p,q);
if(root.val<p && root.val<q) return lowestCommonAncestor(root.right,p,q);
return root.val;
}
}
BM38 在二叉树中找到两个节点的最近公共祖先
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
public int lowestCommonAncestor (TreeNode root, int p, int q) {
if(root==null) return -1;
if(root.val==p||root.val==q) return root.val;
int left=lowestCommonAncestor(root.left,p,q);
int right=lowestCommonAncestor(root.right,p,q);
if(left==-1) return right;
if(right==-1) return left;
return root.val;
}
}
BM39 序列化二叉树
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
String Serialize(TreeNode root) {
if(root==null)return "[]";
StringBuilder res =new StringBuilder("[");
ArrayList<TreeNode> queue =new ArrayList<>();
if(root!=null)queue.add(root);
while(queue.size()!=0){
TreeNode node= queue.remove(0);
if(node!=null){
res.append(node.val+",");
queue.add(node.left);
queue.add(node.right);
}
else res.append("null,");
}
res.deleteCharAt(res.length()-1);
res.append("]");
return res.toString();
}
TreeNode Deserialize(String data) {
if(data.equals("[]"))return null;
String[] vals=data.substring(1,data.length()-1).split(",");
TreeNode root =new TreeNode(Integer.parseInt(vals[0]));
ArrayList<TreeNode> queue=new ArrayList<>();
if(root!=null)queue.add(root);
int i=1;
while(queue.size()!=0){
TreeNode node=queue.remove(0);
if(!vals[i].equals("null")){
node.left=new TreeNode(Integer.parseInt(vals[i]));
queue.add(node.left);
}
i++;
if(!vals[i].equals("null")){
node.right=new TreeNode(Integer.parseInt(vals[i]));
queue.add(node.right);
}
i++;
}
return root;
}
}
BM40 重建二叉树
import java.util.*;
public class Solution {
int[] pre;
HashMap<Integer,Integer> map=new HashMap<>();
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
this.pre=pre;
for(int i=0;i<in.length;i++){
map.put(in[i],i);
}
return dfs(0,0,in.length-1);
}
private TreeNode dfs(int root,int l,int r){
if(l>r) return null;
TreeNode node=new TreeNode (pre[root]);
int i=map.get(pre[root]);
node.left=dfs(root+1,l,i-1);
node.right=dfs(root+i-l+1,i+1,r);
return node;
}
}
BM41 输出二叉树的右视图
/**
* 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 {
List<Integer> res=new ArrayList<>();
List<TreeNode> queue=new ArrayList<>();
public List<Integer> rightSideView(TreeNode root) {
if(root!=null) queue.add(root);
while(queue.size()!=0){
for(int i=queue.size()-1;i>=0;i--){
TreeNode node=queue.remove(0);
if(node.left!=null) queue.add(node.left);
if(node.right!=null) queue.add(node.right);
if(i==0) res.add(node.val);
}
}
return res;
}
}
124. 二叉树中的最大路径和
/**
* 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 {
int sum=Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
dfs(root);
return sum;
}
private int dfs(TreeNode root){
if(root==null) return 0;
int left=Math.max(dfs(root.left),0);// 左子树提供的最大路径和
int right=Math.max(dfs(root.right),0);//右子树提供的最大路径和
sum=Math.max(sum,root.val+left+right);
return root.val+Math.max(left,right);
}
}
543. 二叉树的直径
/**
* 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 {
int max=0;
public int diameterOfBinaryTree(TreeNode root) {
if(root==null) return 0;
dfs(root);
return max;
}
private int dfs(TreeNode root){
if(root==null) return 0;
int left=dfs(root.left);
int right=dfs(root.right);
max=Math.max(left+right,max);
return Math.max(left,right)+1;
}
}
662. 二叉树最大宽度
/**
* 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 {
//假设满二叉树表示成数组序列,记录节点层数和每一层最左节点的索引
int max = 0;
HashMap<Integer, Integer> map = new HashMap<>();
public int widthOfBinaryTree(TreeNode root) {
dfs(root, 1, 1);
return max;
}
private void dfs(TreeNode root, int level, int i) {
if (root == null) return;
if (!map.containsKey(level)) map.put(level,i);//每一层最左节点的索引
max = Math.max(max, i-map.get(level)+1);
dfs(root.left,level+1,i*2);
dfs(root.right,level+1,i*2+1);
}
}
剑指 Offer 54. 二叉搜索树的第k大节点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int res,k;
public int kthLargest(TreeNode root, int k) {
this.k=k;
dfs(root);
return res;
}
public void dfs(TreeNode root){
if(root==null)return;
dfs(root.right);
if(k==0) return;
if(--k==0)res=root.val;
dfs(root.left);
}
}
230. 二叉搜索树中第K小的元素
/**
* 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 {
int res,k;
public int kthSmallest(TreeNode root, int k) {
this.k=k;
dfs(root);
return res;
}
public void dfs(TreeNode root){
if(root==null) return;
dfs(root.left);
if(k==0)return;
if(--k==0) res=root.val;
dfs(root.right);
}
}
450. 删除二叉搜索树中的节点
/**
* 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 TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (key > root.val) root.right = deleteNode(root.right, key);
else if (key < root.val) root.left = deleteNode(root.left, key);
else {
if (root.left==null) return root.right;
if (root.right==null) return root.left;
TreeNode node = root.right;
while (node.left!=null) node = node.left;
node.left = root.left;
root = root.right;
}
return root;
}
}
572. 另一棵树的子树
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if(root==null) return false;
return recur(root,subRoot)||isSubtree(root.left,subRoot)
||isSubtree(root.right,subRoot);
}
public boolean recur (TreeNode root,TreeNode subRoot){
if(subRoot==null&&root==null) return true;
if(subRoot==null||root==null||(root.val!=subRoot.val)) return false;
return recur(root.left,subRoot.left)&&recur(root.right,subRoot.right);
}
}
208. 实现 Trie (前缀树)
class Trie {
class TireNode {
private boolean isEnd;
TireNode[] next;
public TireNode() {
isEnd = false;
next = new TireNode[26];
}
}
private TireNode root;
public Trie() {
root = new TireNode();
}
public void insert(String word) {
TireNode node = root;
for (char c : word.toCharArray()) {
if (node.next[c - 'a'] == null) node.next[c - 'a'] = new TireNode();
node = node.next[c - 'a'];
}
node.isEnd = true;
}
public boolean search(String word) {
TireNode node = root;
for (char c : word.toCharArray()) {
node = node.next[c - 'a'];
if (node == null) return false;
}
return node.isEnd;
}
public boolean startsWith(String prefix) {
TireNode node = root;
for (char c : prefix.toCharArray()) {
node = node.next[c - 'a'];
if (node == null) return false;
}
return true;
}
}
剑指 Offer 34. 二叉树中和为某一值的路径
class Solution {
List<List<Integer>> res =new ArrayList<>();
List<Integer> path=new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
recur(root,target);
return res;
}
public void recur(TreeNode root,int target){
if(root==null) return;
path.add(root.val);
target-=root.val;
if(target==0&&root.left==null&&root.right==null) res.add(new ArrayList(path));
recur(root.left,target);
recur(root.right,target);
path.remove(path.size()-1);
}
}
JZ33判断一个数组是不是某二叉搜索树的后序遍历
public class Solution {
public boolean VerifySquenceOfBST(int [] post) {
if(post.length==0) return false;
return recur(post,0,post.length-1);
}
public boolean recur(int[] post,int i,int j){
if(i>=j)return true;
int k=i;
while(post[k]<post[j]) k++;
int m=k;
while(post[k]>post[j]) k++;
return k==j&&recur(post,i,m-1)&&recur(post,m,j-1);
}
}