Wang Dao_Example 10.1バイナリツリートラバーサル(清華再テストの質問)

トピック

最初にトラバースされる文字列の文字列を入力し、この文字列に基づいてバイナリツリーを構築します。
たとえば、1次トラバーサル文字列ABC ## DE#G ## F ###を入力します。#はスペースを表し、スペース文字列は空のツリーを表します。ツリーを構築した後、結果を出力するためにバイナリツリーをトラバースします。

総括する

  • 木の構造
struct TreeNode{
    
    
	char data;
	TreeNode* leftChild;
	TreeNode* rightChild;
	//表示初始化支持TreeNode(c),即data的值为c,left和right为NULL 
	TreeNode(char c):data(c),leftChild(NULL),rightChild(NULL){
    
    } 
	
}; 
  • ツリー構築プロセス:番号はプレオーダートラバーサルの結果に従って構築されるため、最初にルートノードルートを新しく作成し、次に再帰を使用してそれぞれ左側のサブツリーと右側のサブツリーを構築します。
//根据输入的前序遍历的值构造二叉树,函数返回根节点  
TreeNode* Build(int& position,string str)
{
    
    
	char c=str[position];++position;
	if(c=='#') return NULL;
	TreeNode* root=new TreeNode(c);
	root->leftChild=Build(position,str);
	root->rightChild=Build(position,str);
	return root; 
}
  • 二分木の非再帰的中次走査に関して、中次走査
    は再帰で非常に簡単に実行できます。非再帰的方法は次のとおりです。
//思路:步骤一:沿着根的左孩子依次入栈,直到左孩子为空,说明已经找到可以输出的节点
//步骤二:栈顶元素出栈 。若元素没有右孩子,继续步骤二。有右孩子,右孩子入栈,转执行一。
void InOrder2(TreeNode* root)
{
    
    
	stack<TreeNode*> a;
	while(root!=NULL||!a.empty()){
    
    
		while(root!=NULL){
    
    
			a.push(root);
			root=root->leftChild;
		}
	    root=a.top();
		cout<<root->data<<' ';
		a.pop();
		root=root->rightChild;
	}
	return;
 } 
  • 二分木の非再帰的なプレオーダートラバーサルは、
    ミドルオーダートラバーサルほぼ同じです。コードの唯一の違いは、ノードのアクセスがスタックの前に配置されることです。
void InOrder2(TreeNode* root)
{
    
    
	stack<TreeNode*> a;
	while(root!=NULL||!a.empty()){
    
    
		while(root!=NULL){
    
    
		    cout<<root->data<<' ';
			a.push(root);
			root=root->leftChild;
		}
	    root=a.top();
		a.pop();
		root=root->rightChild;
	}
	return;
 } 

コード

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
struct TreeNode{
    
    
	char data;
	TreeNode* leftChild;
	TreeNode* rightChild;
	//表示初始化支持TreeNode(c),即data的值为c,left和right为NULL 
	TreeNode(char c):data(c),leftChild(NULL),rightChild(NULL){
    
    } 
	
}; 

//根据输入的前序遍历的值构造二叉树,函数返回根节点  
TreeNode* Build(int& position,string str)
{
    
    
	char c=str[position];++position;
	if(c=='#') return NULL;
	TreeNode* root=new TreeNode(c);
	root->leftChild=Build(position,str);
	root->rightChild=Build(position,str);
	return root; 
}
void InOrder(TreeNode* root)
{
    
    
	if(root==NULL) return;
	InOrder(root->leftChild);
	cout<<root->data<<' ';
	InOrder(root->rightChild);
	return;
 } 
int main()
{
    
    
	string str;
	cin>>str;
	int position=0;//记录str的下标 
	TreeNode* root=Build(position,str);//根据前序遍历的结果建树 
	InOrder(root);//中序遍历,输出结果 	
	return 0;
	
}

おすすめ

転載: blog.csdn.net/weixin_45019830/article/details/114850962