3月23日
回文判断就用栈, 首先找到中点.
回文链表
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Palindrome {
public boolean isPalindrome(ListNode pHead) {
// write code here
Stack<Integer> stack = new Stack();
ListNode fast = pHead, slow = pHead;
while (fast != null && fast.next != null) {
stack.push(slow.val);
fast = fast.next.next;
slow = slow.next;
}
if (fast != null) {
slow = slow.next;
}
while (slow != null) {
if (stack.pop() != slow.val) {
return false;
}
slow = slow.next;
}
return true;
}
}
3月25日
返回树中某一深度的所有节点组成的链表
public class TreeLevel {
ListNode pre = new ListNode(-1);
ListNode cur = pre;
public ListNode getTreeLevel(TreeNode root, int dep) {
// write code here
if (root == null || dep <= 0) {
return null;
}
if (dep == 1) {
cur.next = new ListNode(root.val);
cur = cur.next;
}else {
getTreeLevel(root.left, dep-1);
getTreeLevel(root.right, dep-1);
}
return pre.next;
}
}
检查是否是二叉搜索树
public boolean checkBST(TreeNode root) {
// write code here
if (root == null) {return false;}
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
int tmp = Integer.MIN_VALUE;
while (cur != null || !stack.isEmpty()) {
if (cur != null) {
stack.push(cur);
cur = cur.left;
}else {
cur = stack.pop();
if (cur.val <= tmp) {
return false;
}
tmp = cur.val;
cur = cur.right;
}
}
return true;
}
二叉树中和为某一值的路径(从根到叶)
public class Solution {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
ArrayList<Integer> sub = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if (root == null) return res;
sub.add(root.val);
target -= root.val;
if (target == 0 && root.left == null && root.right == null) {
res.add(new ArrayList(sub));
}
FindPath(root.left, target);
FindPath(root.right, target);
sub.remove(sub.size()-1);
return res;
}
}
3月26日
//图的深度优先
public void depthFirst(int index, boolean[] visit) {
//打印当前节点
print(getValueOfIndex(index);
//将访问标志为true
visit[index] = true;
//获得第一个临接节点
int w = getFirstNeighbor(index);
while (w != -1) {
if (!visit[w]) {
depthFirst(w, visit);
}
//获得下一个临接节点
w = getNextNeighbor(index);
}
}
private void getFirstNeighbor(int index) {
if (index <0 || index > graphic.size()) {
throw new Exception();
}
for (int i = 0; i < graphic.size(); i++) {
if (graphic[i][index] != 0) {
return i;
}
}
return -1;
}
private void getNextNeighbor(int index, int w) {
for (int i = w+1; i < graphic.size(); i++){
if (graphic[i][index] != 0) {
return i;
}
}
}
//图的广度优先
public void broadFirst(int index, boolean[] visit) {
Queue<Integer> queue = new LinkedList();
print(index);
visit[index] = true;
queue.add(index);
while (!queue.isEmpty()){
int m = queue.remove();
int n = getFirstNeighbor(m);
while (n != -1){
if (!visit[n]){
print(n);
visit[n] = true;
queue.add(n);
}
n = getNextNeighbor(m, n);
}
}
}
}