acwing-02
合并两个排序的链表(简单)
输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。
样例
输入:1->3->5 , 2->4->5
输出:1->2->3->4->5->5
- 设置哨兵指向头结点小的链表作为主链表
- 遍历另一条链表,找到正确的位置将链表结点一个一个插到主链表中
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode *dump,*p,*q,*pre,*cur;
if(l1==NULL&&l2==NULL)return NULL;
if(l1==NULL)return l2;
if(l2==NULL)return l1;
if(l1->val<=l2->val)
dump->next=l1;
else
dump->next=l2;
pre=dump;
p=dump->next;
q=(p==l1)?l2:l1;
while(q!=NULL){
while(p!=NULL&&p->val<=q->val){pre=p;p=p->next;}
pre->next=q;
cur=q->next;
q->next=p;
q=cur;
pre=pre->next;
}
return dump->next;
}
};
树的子结构(简单)
输入两棵二叉树A,B,判断B是不是A的子结构。
我们规定空树不是任何树的子结构。
样例
树A:
8
/ \
8 7
/ \
9 2
/ \
4 7
树B:
8
/ \
9 2
返回 true ,因为B是A的子结构。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) {
if(pRoot1==NULL||pRoot2==NULL)return false;
if(isSame(pRoot1,pRoot2))return true;
return hasSubtree(pRoot1->left,pRoot2)||hasSubtree(pRoot1->right,pRoot2);
}
bool isSame(TreeNode *root1,TreeNode *root2){
if(root2==NULL)return true;
if(root1==NULL||root1->val!=root2->val)return false;
return isSame(root1->left,root2->left)&&isSame(root1->right,root2->right);
}
};
二叉树的镜像(简单)
输入一个二叉树,将它变换为它的镜像。
样例
输入树:
8
/ \
6 10
/ \ / \
5 7 9 11
[8,6,10,5,7,9,11,null,null,null,null,null,null,null,null]
输出树:
8
/ \
10 6
/ \ / \
11 9 7 5
[8,10,6,11,9,7,5,null,null,null,null,null,null,null,null]
class Solution {
public:
void mirror(TreeNode* root) {
if(root==NULL)return ;
TreeNode *t;
t=root->left;
root->left=root->right;
root->right=t;
mirror(root->left);
mirror(root->right);
}
};