트리에 있는 두 노드의 가장 가까운 공통 부모 노드를 찾습니다
경로를 찾는 코드를 붙여라: 귀속적인 사고방식이기도 하다
// , 、 、 。
#include <iostream>
#include <stack>
using namespace std;
struct TreeNode 
{
	int value;
	TreeNode *pLeft;
	TreeNode *pRight;
};
void addTreeNode(TreeNode *&pRoot,int *index,int &iCurrent){
	if(-1 != index[iCurrent]){
		TreeNode *pCurrent = new TreeNode;
		pCurrent->value = index[iCurrent++];
		pCurrent->pLeft = NULL;
		pCurrent->pRight = NULL;
		pRoot = pCurrent;
		addTreeNode(pRoot->pLeft,index,iCurrent);
		addTreeNode(pRoot->pRight,index,iCurrent);
	}else{
		++iCurrent;
	}
}
void createTree(TreeNode *&pRoot,int *index){
	int iCurrent = 0;
	addTreeNode(pRoot,index,iCurrent);
}
bool findA(TreeNode *pRoot,int value,stack<TreeNode*> &s){
	if(pRoot ==NULL){
		return false;
	}
	if(pRoot->value == value){
		s.push(pRoot);
		return true;
	}else if(findA(pRoot->pLeft,value,s)){
		s.push(pRoot);
		return true;
	}else if(findA(pRoot->pRight,value,s)){
		s.push(pRoot);
		return true;
	}
	return false;
}
void preOrder(TreeNode *pRoot){
	if(pRoot != NULL){
		cout << pRoot->value << " ";
		preOrder(pRoot->pLeft);
		preOrder(pRoot->pRight);
	}
}
int main(){
	int index[] = {8,6,5,-1,-1,-1,10,11,-1,-1,-1};// 
	TreeNode *pRoot = NULL;
	createTree(pRoot,index);// 
/*
         8
        / \
       6   10
      /    /
     5    11
*/
	preOrder(pRoot);
	stack<TreeNode*> s;
	bool ret = findA(pRoot,11,s);
	cout << endl;
	if(ret){
		while(!s.empty()){
			cout << s.top()->value << " ";
			s.pop();
		}
		cout << endl;
	}
	
	return 1;
}이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.