腾讯

1,合并两个有序链表

代码注释掉的分别是链表结构和递归解决的版本

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {/*
        if(pHead1==NULL)
            return pHead2;
        else if(pHead2==NULL)
            return pHead1;
        if(pHead1->val<pHead2->val){
            pHead1->next=Merge(pHead1->next,pHead2);
            return pHead1;
        }
        if(pHead1->val>=pHead2->val){
            pHead2->next=Merge(pHead1,pHead2->next);
            return pHead2;
    }*/
        ListNode* p;
        ListNode* head;
        if(pHead1==NULL)
            return pHead2;
        if(pHead2==NULL)
            return pHead1;
        if(pHead1->val<=pHead2->val){
            head=pHead1;
            pHead1=pHead1->next;
        }
        else{
            head=pHead2;
            pHead2=pHead1->next;
        }
        p=head;
        while(pHead1!=NULL&&pHead2!=NULL){
            if(pHead1->val<pHead2->val){
                p->next=pHead1;
                pHead1=pHead1->next;
                p=p->next;
            }
            else{
                p->next=pHead2;
                pHead2=pHead2->next;
                p=p->next;
            }
        }
        if(pHead1==NULL){
            p->next=pHead2;
        }
        if(pHead2==NULL){
            p->next=pHead1;
        }
        return head;
    }
};

2,找出最大二叉搜索树的拓扑结构

给定一颗二叉树,已知所有节点的值都不一样, 返回其中最大的且符合搜索二叉树条件的最大拓扑结构的大小。拓扑结构是指树上的一个联通块。

输入描述:

第一行输入两个整数 n 和 root,n 表示二叉树的总节点个数,root 表示二叉树的根节点。
以下 n 行每行三个整数 fa,lch,rch,表示 fa 的左儿子为 lch,右儿子为 rch。(如果 lch 为 0 则表示 fa 没有左儿子,rch同理)
ps:节点的编号就是节点的值。

首先因为节点的编号是从1–n,并且编号就是节点的值,所以值也为1–n,所以可以使用两个数组对节点及其左右孩子进行记录,以此构建二叉树。

/*输入
3 2
2 1 3
1 0 0
3 0 0
输出
3*/
#include<iostream>
using namespace std;
bool bst(int root,int flag,int* lc,int *rc){
	if(root==0)
		return false;
	else if(root==flag)
		return true;
	else {
		if(root>flag)
			return bst(lc[root],flag,lc,rc);
		else
			return bst(rc[root],flag,lc,rc);
	}
}
int max(int root1,int root2,int *lc,int *rc){
	if(root1*root2!=0&&bst(root1,root2,lc,rc))
		return max(root1,lc[root2],lc,rc)+max(root1,rc[root2],lc,rc)+1;
	return 0;
}
void solution(int root,int* lc,int* rc,int& count){
	if(root==0)
		return;
	int kk=max(root,root,lc,rc);
	count=(count>kk?count:kk);
	solution(lc[root],lc,rc,count);
	solution(rc[root],lc,rc,count);
}
int main(){
	int n;//数量
	int root;//根节点
	while(cin>>n>>root){
		int lch[n+1];
		int rch[n+1];
		for(int i=0;i<n;i++){
			int fa;
			cin>>fa;
			cin>>lch[fa]>>rch[fa];
		}
		int count=0;
		solution(root,lch,rch,count);
		cout<<count;
	} 
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/yang15309214213/article/details/106032875