LeetCode解题路程(6)

235. Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

_______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

就是查找树里找2个节点的最近的父节点

题目不难,很久没处理树的结构了,一直在做数组,这个就练练手吧

代码很简单,同时查找两个结点,当第一次出现分歧时,那个就是最近的父节点

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    TreeNode searchNode = root;
    while(searchNode!=p && searchNode!=q){
        if(searchNode.val>p.val && searchNode.val>q.val){
            searchNode = searchNode.left;
        }else if(searchNode.val<p.val && searchNode.val<q.val){
            searchNode = searchNode.right;
        }else{
            break;
        }
    }
    return searchNode;
}

再写个解法,这个难理解一点

再查找树中,2个结点的最近父节点,一定是从root往下第一个值位于两个结点值中间的那个结点

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
	int max = Math.max(p.val, q.val);
	int min = Math.min(p.val, q.val);
	while (max<root.val || min>root.val)){
        if(root.val<min){
              root = root.right;
        }else{
              root = root.left;
        }
    }
	return root;
}

237. Delete Node in a Linked List

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

很简单的一道题,学过数据结构的都知道,如果要在单向链表中删除一个结点,那么需要获取这个结点之前的结点

但是这道题只给了需要删除的那个结点,只能根据题意投机取巧,手动将这个结点的值变为下个结点,并删去下个结点

Java代码

public void deleteNode(ListNode node) {
    node.val = node.next.val;
    node.next = node.next.next;
}

C++代码,这里放上C++代码是因为感受到了指针的强大,本来脑子很蠢的想 node = node.next;

这在Java中只是替换了变量的指向罢了,真正操作对象需要指针才可以

void deleteNode(ListNode* node) {
    *node = *node->next;
}

但这是不适合的写法,因为没有回收被删去的那个对象,需要这样写

void deleteNode(ListNode* node) {
    auto next = node->next;
    *node = *next;
    delete next;
}

这时又感受到Java垃圾回收的强大了

不过这道题还是很蠢,一般不会这么出题的吧

 

转载于:https://my.oschina.net/u/2486965/blog/751359

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值