移除链表元素
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
法一:增加一个节点代替当前的头指针,这样如果头指针为应该跨过的指针,也可以用加的那个指针跨过。
public ListNode removeElements(ListNode head, int val) {
ListNode header = new ListNode(-1);
header.next = head;
ListNode cur = header;
while (cur.next != null){
if (cur.next.val == val){
// 这里判断cur.next != null 很好,可以使这句不会空指针异常
cur.next = cur.next.next; // 这句是跨过节点
}else {
cur = cur.next; // 移动指针
}
}
return header.next;
}
法二:
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
ListNode cur = head,naxt = head.next;
while (cur != null && naxt != null){
if (cur.val == val){
cur = cur.next;
head = cur;
naxt = cur.next;
continue;
}
if (naxt.val == val){
cur.next = naxt.next;
naxt = cur.next;
continue;
}
cur = cur.next;
naxt = cur.next;
}
if (cur.val == val){
return cur.next;
}
return head;
}
二叉树的所有路径
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入: 1 / \ 2 3 \ 5 输出: ["1->2->5", "1->3"] 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
List<String> result;
public List<String> binaryTreePaths(TreeNode root) {
result = new ArrayList<>();
getPath(root,"");
return result;
}
private void getPath(TreeNode root,String path){
if (root == null) return;
path = path + root.val;
if (root.left != null)
getPath(root.left,path+"->");
if (root.right != null)
getPath(root.right,path+"->");
if (root.left == null && root.right == null)
result.add(path);
}