1.二叉树中和为某一值的路径
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
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 {
private ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
private ArrayList<Integer> list = new ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if (root == null) {
return listAll;
}
list.add(root.val);
target -= root.val;
if (root.left == null && root.right == null && target == 0) {
listAll.add(new ArrayList<Integer>(list));
}
FindPath(root.left, target);
FindPath(root.right, target);
list.remove(list.size() - 1);
return listAll;
}
}
target -= root.val; (更新target值)
listAll.add(new ArrayList<Integer>(list));(创建新的符合条件的list,否则list会指向同一个地址)
2.复杂的链表复制
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if (pHead == null) {
return null;
}
CloneNew(pHead);
CloneRandom(pHead);
return Separate(pHead);
}
// 复制原链表,原结点的next指向复制结点
private static void CloneNew(RandomListNode pHead) {
RandomListNode pNode = pHead;
while (pNode != null) {
RandomListNode pClone = new RandomListNode(pNode.label);
pClone.next = pNode.next;
pClone.random = null;
pNode.next = pClone;
pNode = pClone.next;
}
}
// 复制random
private static void CloneRandom(RandomListNode pHead) {
RandomListNode pNode = pHead;
while (pNode != null) {
RandomListNode pClone = pNode.next;
if (pNode.random != null) {
pClone.random = pNode.random.next;
}
pNode = pClone.next;
}
}
// 分离链表
private static RandomListNode Separate(RandomListNode pHead) {
RandomListNode pNode = pHead;
RandomListNode pCloneHead = pHead.next;
while (pNode != null) {
RandomListNode pClone = pNode.next;
pNode.next = pClone.next;
pClone.next = pClone.next == null ? null : pClone.next.next; // 偶数结点
pNode = pNode.next;
}
return pCloneHead;
}
}
注意复制结点永远是原结点next指针指向的结点