List2 深度优先搜索
今天更新的是深度优先搜索一节。链表的题明天更新。深度优先搜索也算是老生常谈的题型了,一些经典题目(像一些二叉树递归,岛屿数量之类的题)也是能写出来的。像前序和中序序列还原二叉树这些题之前还比较迷糊,现在好很多了。总之学习就是一个发现自己不足并改进的过程,加油鸭!
- 中等 验证二叉搜索树 Validate Binary Search Tree
20.07.13
思路:DFS
class Solution {
private double last = -Double.MAX_VALUE;
public boolean isValidBST(TreeNode root) {
if(root == null)return true;
if(isValidBST(root.left)){
if(last < root.val){
last = root.val;
return isValidBST(root.right);
}
}
return false;
}
}
- 困难 恢复二叉搜索树 Recover Binary Search Tree
20.07.13
思路:中序遍历必须是有序的,不然交换结点的值。
class Solution {
private TreeNode t1,t2,pre;
public void recoverTree(TreeNode root) {
inorder(root);
int temp = t1.val;
t1.val = t2.val;
t2.val = temp;
}
public void inorder(TreeNode root){
if(root == null) return ;
inorder(root.left);
if(pre != null && pre.val > root.val){
if(t1 == null) t1 = pre;
t2 = root;
}
pre = root;
inorder(root.right);
}
}
- 简单 相同的树 Same Trees
20.07.13
思路:递归完事
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
if((p!=null && q==null)||(p==null && q!=null)) return false;
if(q.val != p.val) return false;
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}
}
- 简单 对称二叉树 Symmetric Tree
20.07.13
思路:如上题,写成两个树就行了。
class Solution {
public boolean isSymmetric(TreeNode root) {
return isMirror(root,root);
}
public boolean isMirror(TreeNode p,TreeNode q){
if(p == null && q == null) return true;
if((p != null && q == null)||(p == null && q != null)) return false;
if(p.val != q.val) return false;
return isMirror(p.left,q.right) && isMirror(p.right,q.left);
}
}
- 简单 二叉树的最大深度 Maximum Depth of Binary Tree
20.07.13
思路:递归。
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}
- 中等 从前序遍历与中序遍历序列构造二叉树 Construct Binary Tree from Preorder and Inorder Traversal
20.07.13
思路:对于一个子树,前序为根结点,从左到这个值的中序序列为这个的左子树。这种题还要多加复习。
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return pre_order(0,preorder.length-1,0,inorder.length-1,preorder,inorder);
}
public TreeNode pre_order(int leftpre,int rightpre,int leftin,int rightin,int[] pre, int[] in){
if(leftpre > rightpre || leftin > rightin) return null;
TreeNode root = new TreeNode(pre[leftpre]);
int rootin = leftin;
while(rootin <= rightin && in[rootin] != pre[leftpre]) rootin++;//在前序和中序序列中找到根结点
int left = rootin - leftin;//是找出所有根结点的左子树的区间,在中序序列中找
root.left = pre_order(leftpre+1,leftpre+left,leftin,rootin-1,pre,in);
root