首先解析二叉树 Lowest Common Ancestor of a Binary Search Tree ,寻找二叉树中某两个节点中路径最短的根节点。如下,2与8 ,最短路径根节点为6.
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
算法分析:
采用DFS, 若节点,p,q的最大值比root要下,那么可以确定所求的节点肯定在root的左边,反之若p,q的最小值比root节点要大,则说明所求节点肯定在root的右边。
其余则是,root,位于p,q中间,则直接返回 root.
然后采用递归方法,一级一级递归下去,则可找出目的节点。
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || p == null || q == null){
return null;
}
if(Math.max(p.val,q.val) < root.val){
return lowestCommonAncestor(root.left,p,q);
}else if(Math.min(p.val,q.val) > root.val) {
return lowestCommonAncestor(root.right,p,q);
}else {
return root;
}
}
}
接下来,单链表排序。Sort a linked list in O(n log n) time using constant space complexity.
对于时间复杂度和空间复杂度的要求如上,时间复杂度为nlogn,那么我们就用归并排序来做。
算法分析:
1.利用归并排序,第一点要找出链表的中间点。
2.归并排序。
3.排序后合并两个有序的链表l1,l2,。
这里我们用C++代码来实现:
class Solution {
public:
ListNode* getMiddleOfList(ListNode* node){
ListNode* slow =head;
ListNode* fast = head;
while(fast->next && fast->next->next){
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* sortList(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* middle = getMiddleOfList(head);
ListNode* next = middle->next;
middle->next = NULL;
return mergeList(sortList(head),sortList(next));
}
ListNode* mergeList(ListNode* l1,ListNode* l2){
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
ListNode* dummpy = new ListNode(-1);
ListNode* cur = dummpy;
while(l1!=NULL && l2!=NULL){
if(l1->val <= l2->val){
cur->next = l1;
l1 = l1->next;
} esle{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if(l1)
cur->next = l1;
if(l2)
cur->next = l2;
return dummpy->next;
}
};
好啦,齐活了,今天的一更完成,晚上回去继续补上昨天漏掉的。