Sword finger Offer summary part II

Posted by nivosh on Sun, 16 Jan 2022 20:44:37 +0100

Interview question 16: integer power of value
Title: implement the function double power(double base,int exponent) to find the exponent power of the base. Library functions must not be used and large numbers do not need to be considered. Implement Pow function in C library function.

bool g_InvalidInput=false;
double power(double base,int exponent)
{
	g_InvalidInput=false;
	if(equal(base,0.0)&&exponent<0)
	{
		g_InvalidInput=true;
		return 0.0;
	}
	unsigned int absExponent=(unsigned int)(exponent);
	if(exponent<0)
	{
		absExponent=(unsigned int)(-exponent);
	}
	double result=PowerWithUnsignedExponent(base,absExponent);
	if(exponent<0)//Take the reciprocal
	{
		result=1.0/result;
	}
	return result;
}
double PowerWithUnsignedExponent(base,absExponent)
{
	double result=1.0;
	for(int i=1;i<=absExponent;i++)
	{
		result*=base;
	}
	return result;
]

If the number of exponent is too large, the calculation of the for loop is also large, which can be improved

double PowerWithUnsignedExponent(double base,unsigned int absExponent)
{
	if(absExponent==0)
	{
		return 1;
	}
	if(absExponent==1)
	{
		return base;
	}
	double result=PowerWithUnsignedExponent(base,absExponent>>1);
	resutl*=result;
	if(exponent&1==1)//if(exponent%2==1) bit operator is relatively fast, the last bit of binary digit is 1, which is odd, otherwise it is even
	{
		result*=base;
	}
	return result;
]

Interview question 17: print from 1 to the maximum n digits
Title: enter the number m and print out the n-digit decimal number from 1 to the maximum in order. For example, enter 3 and print 1, 2 and 3 until the maximum 3 digits are 999

void PrintMaxOfNDigits(int n)
{
	int numbers=1;
	int i=0;
	while(i<n)//while(i++<n)
	{
		numbers*=10;
		i++;
	}
	for(i=1;i<numbers;++i)
	{
		printf("%d\t",i);
	}
}

However, the range of n is not considered. If it is a large number, it will exceed the range of int. we can use unsigned int or long long. Therefore, we can use string or array to represent large numbers. Because the maximum number is n bits, we need a string with a length of n+1. The last bit of the string is the terminator '/ 0'. When the actual number is not enough n bits, fill 0 in the first half of the string We need to do two things: one is to simulate addition on numbers expressed in strings; The second is to print out the numbers expressed in strings.

void PrintToMaxOfDigits(int n)
{
	if(n<=0)
	{
		return;
	}
	char *number=new char[n+1];
	menset(number,'0',n);
	number[n]='\0';
	while(!Increment(number))//String analog addition
	{
		PrintNumber(number);//Print numbers
	}
	delete[]number;
}
bool Increment(char*number)
{
	bool isOverflow=false;
	int nTakeOver=0//carry
	int nLength=strlen(number);
	for(int i=nLength-1;i>=0;i--)
	{
		int nSum=number[i]-'0'+nTakeOver;
		if(i==nLength-1)
		{
			nSum++;
		}
		if(nSum>=10)//Generate carry
		{
			if(i==0)
			{
				isOverflow=true;
			}
			else
			{
				nSum-=10;
				nTakeOver=1;
				number[i]=nSum+'0';
			}

		}
		else
		{
			number[i]=nSum+'0';
			break;//Exit directly without carry and add only one
		}
	}
}
void PrintNumber(char * number)
{
	bool isBeginning0=true;
	int n=strlen(number);
	for(int i=0;i<n;++i)
	{
		if(isBeginning0&&number[i]!='0')
		{
			isBeginning0=true;
		}
		if(!isBeginning0)
		{
			printf("%c",number[i])
		}
	}
	printf("\t");

}

The second solution is fully arranged. Each bit is arranged on one side from 0 to 9, and the first 0 is not printed.

void PrintToMaxOfDigits(int n)
{
	if(n<=0)
	{
		return;
	}
	char*number=new char[n+1];
	number[n]='\0';
	for(int i=0;i<10;++i)
	{
		number[0]=i+'0';
		PrintToMaxOfNDigitsRecursively(number,n,0);
	}
	delete number;
}
void PrintToMaxOfNDigitsRecursively(char*number,int length,int index)
{
	if(index==length-1)
	{
		printNumber(number);
		return;
	}
	for(int i=0;i<10;++i)
	{
		number[index+1]=i;
		PrintToMaxOfNDigitsRecursively(number,length,index+1);//Recursion after setting the next bit
	}
}

Interview question 18: delete the node of the linked list
Topic 1: delete linked list nodes in O(1) time
Given the head pointer and a node pointer of the one-way linked list, define a function to delete the node in O(1) time.

struct ListNode
{
	int m_Value;
	ListNode *m_pNext;
};
void DeleteNode(ListNode**PListHead,ListNode*pToBeDeleted)
{
	if(!PListHead||!pToBeDeleted)
	{
		return;
	}
	if(pToBeDeleted->m_pNext!=nullptr)//The node to be deleted is not a tail node
	{
		ListNode*pNode=pToBeDeleted->m_pNext;
		pToBeDeleted->m_Value=pNode->m_Value;
		pToBeDeleted->m_pNext=pNode->m_pNext;
		delete pNode;
		pNode=nullptr;
	}
	else if(*PListHead=pToBeDeleted)//The linked list has only one node. Delete the head and tail nodes
	{
		delete pToBeDeleted;
		pToBeDeleted=nullptr;
		*PListHead=nullptr;
	}
	else//There are many nodes. Delete the tail node
	{
		ListNode*pNode=*PListHead;
		while(pNode->m_pNext!=pToBeDeleted)
		{
			pNode=pNode->m_pNext;
		}
		pNode->m_pNext=nullptr;
		delete pToBeDeleted;
		pToBeDeleted=nullptr;
	}
}

Topic 2: delete duplicate nodes in the linked list
How to delete duplicate nodes in a sorted linked list?

void DeleteDuplication(ListNode**pHead)
{
	if(*pHead&&pHead)
	{
		return;
	}
	ListNode*pPreNode=nullptr;
	ListNode*pNode=*pHead;
	while(pNode!=nullptr)
	{
		ListNode*pNext=pNode->m_pNext;
		bool needDelete=false;
		if(pNext!=nullptr&&pNext->m_nValue==pNode->m_nValue)
		{
			needDelete=true;
		}
		if(!needDelete)
		{
			pPreNode=pNode;
			pNode=pNext;
		}
		else
		{
			int value=pNode->m_nValue;
			ListNode*pToBeDel=pNode;
			while(pToBeDel->m_nValue==value&&pToBeDel!=nullptr)
			{
				pNext=pToBeDel->m_pNext;
				delete pToBeDel;
				pToBeDel=nullptr;
				pToBeDel=pNext;
			}
			if(pPreNode==nullptr)
			{
				*pHead=pNext;
			}
			else{
				pPreNode->m_pNext=pNext;
			}

			pNode=pNext;
		}
		
	}
}

Interview question 19: regular expression matching
Title: please implement a function to match the containing '.' Regular expressions for and ''. Character '.' in mode Represents any character, and '' indicates that the character before it can appear any time (including 0 times).
When the second character in the mode is not ''. If the first character in the string matches the first character in the pattern, move one character after both the string and the pattern, and then match the remaining strings and patterns. Returns false if the first character in the string does not match the first character in the pattern.
When the second character in the mode is' '. One option is to move two characters backward on the mode. This is equivalent to that '' and the characters before it are ignored because '' can match 0 characters in the string. If the first character in the pattern matches the first character in the string, move one character backward on the string, and there are two options on the pattern: you can move two characters backward on the pattern or keep the pattern unchanged

bool match(char*str,char*pattern)
{
	if(str==nullptr||pattern==nullptr)
	{
		return false;
	}
	return matchCore(str,pattern);
}
bool matchCore(char*str,char*pattern)
{
	if(*str=='\0'&&*pattern=='\0')
	{
		return true;
	}
	if(*str!='\0'&&*pattern=='\0')
	{
		return false;
	}
	if(*(pattern+1)=='*')
	{
		if(*str==*pattern||(*pattern=='.'&&*str!='\0'))
		{
			return matchCore( str+1,pattern+2)||matchCore(str,pattern+2)||matchCore(str+1,pattern);
		}
		else
		{
			//Ignore '*'
			return matchCore(str,pattern+2);
		}
	}
	if(*str==*pattern||(*pattern=='.'&&*str!='\0'))
	{
		return matchCore(str+1,pattern+1);
	}
	return false;
}

Interview question 20: strings representing numeric values
Title: please implement a function to judge whether the string represents a numeric value (including integer and decimal).

bool isNumberic(const char *str)
{
	if(str==nullptr)
	{
		return false;
	}
	//Scan the integers first
	bool numberic=scanInteger(&str);
	if(*str=='.')
	{
		++str;
		numberic=scanUnsignedInteger(&str)||numberic;
		
	}
	if(*str=='e'||*str=='E')
	{
		++str;
		numberic=numberic&&scanInteger(&str);
		
	}
	//12e5.4 is not a decimal. Part C cannot have other characters'. '
	return numberic&&*str=='\0';
}
bool scanInteger(const char**str)
{
	if(**str=='+'||**str=='-')
	
	{
		++(**str);
	}
	return scanUnsignedInteger(str);
}
bool scanUnsignedInteger(const char**str)
{
	const char*before=*str;
	while(**str!='\0'&&**str>='0'&&**str<='9')
	{
		++(**str);
	}
	return *str>before;
	
}

Interview question 21: adjust the array order so that odd numbers precede even numbers
Title: enter an integer array and implement a function to adjust the order of numbers in the array so that all odd numbers are in the first half of the array and all even numbers are in the second half of the array

void ReorderOddEven(int*pData,unsigned int length)
{
	if(pData==nullptr||length==0)
	{
		return;
	}
	int *pBegin=pData;
	int *pEnd=pData+length-1;
	while(pBegin<pEnd)
	{
		while(pBegin<pEnd&&(*pBegin&0x1)!=0)
		{
			pBegin--;
		}
		while(pBegin<pEnd&&(*pBegin&0x1)!=0)
		{
			pEnd--;
		}
		if(pBegin<pEnd)
		{
			temp=*pBegin;
			*pBegin=*pEnd;
			*pEnd=temp;
		}
	}
}
The function is decoupled into two parts: one is the standard to judge whether the number should be in the first half or the second half of the array; The second is the operation of splitting arrays.
void Reorder(int*pData,unsigned int length,bool(*func)(int))
{
	if(pData==nullptr||length==0)
	{
		return;
	}
	int *pBegin=pData;
	int *pEnd=pData+length-1;
	while(pBegin<pEnd)
	{
		while(pBegin<pEnd&&(*pBegin&0x1)!=0)
		{
			pBegin--;
		}
		while(pBegin<pEnd&&(*pBegin&0x1)!=0)
		{
			pEnd--;
		}
		if(pBegin<pEnd)
		{
			temp=*pBegin;
			*pBegin=*pEnd;
			*pEnd=temp;
		}
	}
}
bool isEvent(int n)
{
	return (n&1==0);
}
void RecoderOddEven(int*pData,unsigned int length)
{
	Reorder(pData,length,isEvent);
}

Interview question 22: the penultimate node in the linked list
Title: enter a linked list and output the K-th node of the linked list
Assuming that the whole linked list has n nodes, the penultimate K node is n+1-k nodes from the beginning. Just take n-k+1 steps from the beginning.
In other words, we need to traverse the linked list twice. The first one counts the number of nodes in the linked list, and the second time we can find the K-th node.

ListNode*FindKthToTail(ListNode*pListHead,unsigned int k)
{
	if(pListHead=nullptr||k=0)
	{
		return nullptr;
	}
	ListNode*pAhead=pListHead;
	ListNode*pBehind=nullptr;
	for(int i=0;i<k-1;i++)
	{
		if(pAhead->m_pNext!=nullptr)
		{
				pAhead=pAhead->m_pNext;
		}
		else
		{
			return nullptr;
		}

	}
	pBehind=pListHead;
	while(pAhead->m_pNext!=nullptr)
	{
		pAhead=pAhead->m_pNext;
		pBehind=pBehind->m_pNext;
	}
	return pBehind;
}

Interview question 23: the entry node of the link in the linked list
Title: if a linked list contains a ring, how to find the entry node of the ring

ListNode*MeetingNode(ListNode*pHead)
{
	if(pHead==nullptr)
	{
		return nullptr;
	}
	ListNode*pSlow=pHead->m_pNext;
	if(pSlow==nullptr)
	{
		return nullptr;
	}
	ListNode*pFast=pSlow->m_pNext;
	while(pFast!=nullptr&&pSlow!=nullptr)
	{
		if(pFast==pSlow)
		{
			return pFast;
		}
		pSlow=pSlow->m_pNext;
		pFast=pFast->m_pNext;
		if(pFast==nullptr)
		{
			return nullptr;
		}
		pFast=pFast->m_pNext;
	}
	return nullptr;
}


ListNode*EntryNodeOfLoop(ListNode*pHead)
{
	ListNode*meetingNode=MeetingNode(pHead);
	if(meetingNode==nullptr)
	{
		return nullptr;
	}
	ListNode*pNode1=meetingNode;
	int nodesLoop=1;
	while(pNode->m_pNext!=meetingNode)
	{
		pNode1=pNode1->m_pNext;
		++nodesLoop;                                                                                                                                                                                                                                                                                 
	}
	pNode1=pHead;
	for(int i=0:i<nodesLoop;i++)
	{
		pNode1=pNode1->m_pNext;
	}
	ListNode*pNode2=pHead;
	while(pNode2!=pNode1)
	{
		pNode1=pNode1->m_pNext;
		pNode2=pNode2->m_pNext;
	}
	return pNode1;
}

Interview question 24: reverse linked list
Title: define a function, input the head node of a linked list, reverse the linked list and output the head node of the inverted linked list.

ListNode*ReverseList(ListNode*pHead)
{
	ListNode*pReverseHead=nullptr
	ListNode*pNode=pHead;
	ListNode*pPrev=nullptr;
	while(pNode!=nullptr)
	{
		ListNode*pNext=pNode->m_pNext;
		if(pNext==nullptr)
		{
			pReverseHead=pNode;
		}
		pNode->m_pNext=pPrev;
		pPrev=pNode;
		pNode=pNext;
	}
	return pReverseHead;
}

Interview question 25: merge two sorted linked lists
Title: enter two incrementally sorted linked lists, merge the two linked lists, and make the nodes in the new linked list still be incrementally sorted.

ListNode*Merge(ListNode*pHead1,ListNode*pHead2)
{
	if(pHead1==nullptr)
	{
		return pHead2; 
	}
	if(pHead2==nullptr)
	{
		return pHead1; 
	}
	ListNode*pMergeHead=nullptr;
	if(pHead1->m_nValue<pHead2->m_nValue)
	{
		pMergeHead=pHead1;
		pMergeHead->m_pNext=Merge(pHead1->m_pNext,pHead2);
	}
	else
	{
		pMergeHead=pHead2;
		pMergeHead->m_pNext=Merge(pHead1,pHead2->m_pNext);
	}
	return pMergeHead;
}

Interview question 26: substructure of tree
Title: input two binary trees a and B to judge whether B is a substructure of A

bool DoesTree1HaveTree2(BinaryTree*pRoot1,BinaryTree*pRoot2)
{
	if(pRoot2==nullptr)
	{
		return true;
	}
	if(pRoot1==nullptr)
	{
		return false;
	}

	if(!equal(pRoot1->m_dbValue,pRoot2->m_dbValue))
	{
		return false;
	}
	return DoesTree1HaveTree2(pRoot1->m_pLeft,pRoot2->m_pLeft)&&DoesTree1HaveTree2(pRoot1->m_pRight,pRoot2->m_pRight);
}
bool equal(int num1,int num2)
{
	if((num1-num2)>-0.0000001&&(num1-num2<0.0000001))
	{
		return true;
	}
	else
	{
		return false;
	}
}
bool HasSubtree(BinaryTree*pRoot1,BinaryTree*pRoot2)
{
	bool result=false;
	if(pRoot2!=nullptr&&pRoot1==nullptr)
	{
		if(equal(pRoot1->m_dbValue,pRoot2->m_dbValue))
		{
			 result=DoesTree1HaveTree2(pRoot1,pRoot2);
		}
		if(!result)
		{
			result=DoesTree1HaveTree2(pRoot1->m_pLeft,pRoot2);
		}
		if(!result)
		{
			result=DoesTree1HaveTree2(pRoot1->m_pRight,pRoot2);
		}
		
	}
	return result;
}

Interview question 27: image of binary tree
Title: Please complete a function, input a binary tree, and the output of the function is its image.

void MirrorRescurively(BinaryTreeNode*pNode)
{
	if(pNode==nullptr)
	{
		return;
	}
	if(pNode->m_pLeft==nullptr&&pNode->m_pRight==nullptr)
	{
		return;
	}
	BinaryTreeNode*pTemp=pNode->m_pLeft;
	pNode->m_pLeft=pNode->m_pRight;
	pNode->m_pRight=pTemp;
	if(pNode->m_pLeft)
	{
		 MirrorRescurively(pNode->m_pLeft);
	}
	if(pNode->m_pRight)
	{
		MirrorRescurively(pNode->m_pRight);
	}
}

Interview question 28: symmetric binary tree
Title: please implement a function to judge whether a binary tree is symmetrical. If a binary tree is the same as its mirror, it is symmetrical

bool isSymmetrical(BinaryTreeNode*pRoot)
{
	return isSymmetrical(pRoot,pRoot);
}
bool isSymmetrical(BinaryTreeNode*pRoot1,BinaryTreeNode*pRoot2)
{
	if(pRoot1==nullptr&&pRoot2==nullptr)
	{
		return true;
	}
	if(pRoot1==nullptr||pRoot2==nullptr)
	{
		return false;
	}
	if(pRoot1->m_nValue!=pRoot2->m_nValue)
	{
		return false;
	}
	return isSymmetrical(pRoot1->m_nLeft,pRoot2->m_nRight)&&isSymmetrical(pRoot1->m_nRight,pRoot2->m_nLeft);
}

Interview question 29: print matrix clockwise
Title: enter a matrix and print out each number in clockwise order from outside to inside

void PrintMatrixClockWisely(int **numbers,int columns,int rows)
{
	if(numbers==nullptr||columns<=0||rows<=0)
	{
		return;
	}
	int start=0;
	while(colums>2*start&&rows>2*start)
	{
		PrintMatrixInCircle(numbers,columns,rows,start);
		start++;
	}
}
void PrintMatrixInCircle(int **numbers,int columns,int rows,int start)
{
	 int endX=columns-1-start;
	 int endY=rows-1-start;
	 for(int i=0;i<endX;i++)
	 {
	 	int number=numbers[start][i];
	 	printNumber(number);
	 }
	 if(endY>start)
	 {
	 	for(int i=start+1;i<endY;i++)
	 	{
	 		int number=numbers[i][endX];
	 		printNumber(number);
	 	}
	 }
	 if(endY>start&&endX>start)
	 {]
	 	for(int i=endX-1;i>start;i--)
	 	{
	 		int number=numbers[i][endY];
	 		printNumber(number);
	 	}
	 }
	 if(endX>start&&endY>start+1)
	 {
	 	for(int i=endY-1;i>start+1;i--)
	 		int number=numbers[i][start];
	 		printNumber(number);
	 }
	 
}
																																																																						

Interview question 30: stack containing min function
Title: define the data structure of the stack. Please implement a min function that can find the smallest element of the stack in this type. The time complexity of calling min, push and pop is O(1)

template<typename T>void StackWithMin<T>::push(T &value)
{
	m_data.push(value);
	if(m_min.size()==0||value<m_data.top())
	{
		m_min.push(value);
	}
	else
	{
		m_min.push(m_data.top());
	}
}
template<typename T>void StackWithMin<T>::pop()
{
	assert(m_min.size()>0&&m_data.size()>0);
	m_daya.pop();
	m_min.popo();
}
template<typename T>constT& StackWithMin<T>::min()const
{
	assert(m_min.size()>0&&m_data.size()>0);
	return m_min.top();
}

Interview question 32: print binary tree from top to bottom
Topic 1: do not print a binary tree from top to bottom

void PrintFromToBottom(BinaryTreeNode*pTreeRoot)
{
	if(!pTreeRoot)
	{
		return;
	}
	std::deque<BinaryTreeNode*>dequeTreeNode;
	dequeTreeNode.push_back(pTreeRoot);
	while(dequeTreeNode.size())
	{
		BinaryTreeNode*pNode=dequeTreeNode.front();
		dequeTreeNode.pop_front();
		printf("%d",pNode->m_nValue);
		if(pNode->m_pLeft)
		{
			dequeTreeNode.push_back(pNode->m_pLeft);
		}
		if(pNode->m_pRight)
		{
			dequeTreeNode.push_back(pNode->m_pRight);
		}
	}
}

Topic 2: Branch printing binary tree from top to bottom

void Print(BinaryTreeNode*pRoot)
{
	if(pRoot==nullptr)
	{
		return;
	}
	std::queue<BinaryTreeNode*>nodes;
	nodes.push(pRoot);
	int nextLevel=0;
	int toBePrinted=1;
	while(!nodes.empty())
	{
		BinaryTreeNode*pNode=nodes.front();
		printf("%d",pNode->m_nValue);
		if(pNode->m_pLeft!=nullptr)
		{
			nodes.push(pNode->m_pLeft);
			++nextlevel;
		}
		if(pNode->m_pRight!=nullptr)
		{
			nodes.push(pNode->m_pRight);
			++nextlevel;
		}
		nodes.pop();
		--toBePrint;
		if(toBePrint==0)
		{
			printf("\n");
			toBePrint=nextLevel;
			nextLevel=0;

		}
	}
}

Topic 3: zigzag printing binary tree

void Print(BinaryTreeNode*pRoot)
{
	if(pRoot==nullptr)
	{
		return;
	}
	std::stack<BinaryTreeNode*>levels[2];
	int current=0;
	int next=1;
	levels[0].push(pRoot);
	while(!levels[current].empty()||levels[next].empty())
	{
		BinaryTreeNode*pNode=levels[current].top();
		levels[current].pop;
		printf("%d",pNode->m_nValue);
		
		if(current==0)
		{
			if(pNode->m_pLeft!=nullptr)
			{
				levels[next].push(pNode->m_pLeft);
				
			}
			if(pNode->m_pRight!=nullptr)
			{
				levels[next].push(pNode->m_pRight);
				
			}
			
		}
		else
		{
			if(pNode->m_pRight!=nullptr)
			{
				levels[next].push(pNode->m_pRight);
				
			}
			if(pNode->m_pLeft!=nullptr)
			{
				levels[next].push(pNode->m_pLeft);
				
			}
		}
		if(levels[current].empty())
		{
			printf("\n");
			curretn=1-current;
			next=1-next;
		}
	}
}

Interview question 33: post order traversal sequence of binary search tree
Title: enter an integer array to judge whether the array is the post order traversal result of a binary search tree. If yes, return true; otherwise, return false.

bool VertfySquenceOfBST(int sequence[],int length)
{
	if(sequence==nullptr||length<=0)
	{
		return false;
	}
	int root=sequence[length-1];
	int i=0;
	for(;i<length-1;++i)
	{
		if(sequence[i]>root){
			break;
		}
	}
	int j=i;
	for(;j<length-1;j++)
	{
		if(sequence[j]<root)
		{
			break;
		}
	}
	bool left=true;
	if(i>0)
	{
		left=VertfySquenceOfBST(sequence,i);
	}
	int right=true;
	if(j<length-1)
	{
		right=VertfySquenceOfBST(sequence+i,length-1-i);
	}
	return (left&&right);
}

Interview question 34: paths with a certain value in a binary tree
Title: enter a binary tree and an integer, and print out all paths where the sum of node values in the binary tree is the input integer. A path is formed from the root node of the tree down to the leaf node.

void FindPath(BinaryTreeNode*pRoot,int expectedSum)
{
	if(pRoot==nullptr)
	{
		return;
	}
	std::vector<int>path;
	int currentSum=0;
	FindPath(pRoot,expectedSum,path,currentSum);
}
void FindPath(BinaryTreeNode*pRoot,int expectedSum,std::vector<int>&path,int currentSum){
	currentSum+=pRoot->m_nValue;
	path.push_back(pRoot->m_nValue);
	bool isLeaf=pRoot->m_pLeft==nullptr&&pRoot-<m_pRight==nullptr;
	if(currentSum==expectedSum&&isLeaf)
	{
		printf("A path is found:");
		std:vector<int>::iterator iter=path.begin();
		for(;iter<path.end();++iter)
		{
			printf("%d\t",*iter);
		}
		print("\n");
	}
	//If it is not a leaf node, it traverses its children
	if(pRoot->m_pLeft!=nullptr)
	{
		FindPath(pRoot->m_pLeft,expectedSum,path,currentSum);
	}
	if(pRoot-<m_pRight!=nullptr)
	{
		FindPath(pRoot-<m_pRight,expectedSum,path,currentSum);
	}
	paht.pop_back();
}

Interview question 35: copy of complex linked list
Title: please implement the function complexlistnodeclone (complexlistnodehead) to copy a complex linked list. In a complex linked list, each node has only one M_ The pnext pointer points to the next node and an m_pSibling pointer points to any node or nullptr in the linked list.

void CloneNodes(ComplexListNode*pHead)
{
	ComplexListNode*pNode=pHead;
	while(pNode!=nullptr)
	{
		ComplexListNode*pClone=new ComplexListNode();
		pClone->m_nValue=pNode->m_nValue;
		pClone->m_pNext=pNode->m_pNext;
		pClone->m_pSibling=nullptr;
		pNode->m_pNext=pClone;
		pNode=pClone->m_pNext;
	}
}
void ConnectSiblingNodes(ComplexListNode*pHead)
{
	ComplexListNode*pNode=pHead;
	while(pNode!=nullptr)
	{
		ComplexListNode*pClone=pNode->m_pNext;
		if(pNode->m_pSibling!=nullptr)
		{
			pClone->m_pSibling=pNode->m_pNext->m_pSibling;
			
		}
		pNode=pClone->m_pNext;
	}
}
ComplexListNode*ReconnectNodes(ComplexListNode*pHead)
{
	ComplexListNode*pNode=pHead;
	ComplexListNode*pCloneHead=nullptr;
	ComplexListNode*pCloneNode=nullptr;
	if(pNode!=nullptr)
	{
		pCloneHead=pCloneNode=pNode->m_pNext;
		pNode->m_pNext=pCloneNode->m_pNext;
		pNode=pCloneNode->m_pNext;
	}
	while(pNode!=nullptr)
	{
		pClone->m_pNext=pNode->m_pNext;
		pClone=pClone->m_pNext;
		pNode->m_pNext=pClone->m_pNext;
		pNode=pNode->m_pNext;
	}
}
ComplexListNode*Clone(ComplexListNode*pHead)
{
	CloneNodes(pHead);
	ConnectSiblingNodes(pHead);
	return ReconnectNodes(pHead);
}

Interview question 36: binary search tree and two-way linked list
Title: enter a binary search tree and convert the binary search tree into a sorted two-way linked list.

BinaryTreeNode*Convert(BinaryTreeNode*pRootOfTree)
{
	BinaryTreeNode*pLastNodeInList==nullptr;
	ConvertNode(pRootOfTree,&pLastNodeInList);
	BinaryTreeNode*pHeadOfList=pLastNodeInList;
	while(pHeadOfList!=nullptr&&pHeadOfList->m_pLeft!=nullptr)
	{
		pHeadOfList=pHeadOfList->m_pList;
	}
	return pHeadOfList;
}
void ConvertNode(BinaryTreeNode*pNode,BinaryTreeNode**pLastNodeInList)
{
	if(pNode==nullptr)
	{
		return;
	}
	BinaryTreeNode*pCurrent=pNode;
	if(pCurrent->m_pLeft!=nullptr)
	{
		ConvertNode(pCurrent->m_pLeft,pLastNodeInList);
	}
	pCurrent->m_pLeft=*pLastNodeInList;
	if(*pLastNodeInList!=nullptr)
	{
		(*pLastNodeInList)->m_pRight=pCurrent;
	}
	*pLastNodeInList=pCurrent;
	if(pCurrent->m_pRight!=nullptr)
	{
		ConvertNode(pCurrent->m_pRight,pLastNodeInList);
	}
}

Interview question 37: serialized binary tree
Title: please implement a function to serialize and deserialize binary trees respectively

void Serialize(BinaryTreeNode*pRoot,string&str)
{
	if(pRoot==nullptr)
	{
		str+="#";		
		return;
	}
	string temp=std::to_string(pRoot->m_pValue);
	str+=temp;
	str+=',';
	
	Serialize(pRoot->m_pLeft,str);
	Serialize(pRoot->m_pRight,str);
}
char* Serialize(TreeNode *root) {    
        if(!root){
            return NULL;
        }
        string str;
        SerializeCore(root, str);
        // Convert str stream to string and return
        int length = str.length();
        char* res = new char[length+1];
        // Convert str stream to string and return
        for(int i = 0; i < length; i++){
            res[i] = str[i];
        }
        res[length] = '\0';
        return res;
}
TreeNode* Deserialize(char *str) {
    if(!str){
       return NULL;
    }
    TreeNode* res = DeserializeCore(&str);
    return res;
}
    TreeNode* DeserializeCore(char** str){
        // When reaching the leaf node, it is called twice and returns null. Therefore, after the construction is completed, the construction of the parent node is returned
        if(**str == '#'){
            (*str)++;
            return NULL;
        }
        // Because integers are represented by strings, one character represents one bit, and first line conversion
        int num = 0;
        while(**str != ',' && **str != '\0'){
            num = num * 10 + ((**str) - '0');
            (*str)++;
        }
        TreeNode* root = new TreeNode(num);
        if(**str == '\0'){
            return root;
        }
        else{
            (*str)++;
        }
        root->left = DeserializeCore(str);
        root->right = DeserializeCore(str);
        return root;
    }
};

Topics: C++ Interview