二叉树的深度优先遍历(递归和非递归方式)

二叉树的深度优先遍历 == 前序遍历

#include <iostream>
#include <stack>

using namespace std;

typedef struct tree
{
	int data;
	struct tree *l_child;
	struct tree *r_child;		
}TreeNode;

TreeNode *insertNode(TreeNode *root,int data)
{
	if(root == NULL)
	{
		TreeNode *newNode = new TreeNode();
		newNode->data = data;
		newNode->l_child = NULL;
		newNode->r_child = NULL;
		root = newNode;
	}
	else if(data < root->data)
	{
		root->l_child = insertNode(root->l_child,data);
	}
	else
	{
		root->r_child = insertNode(root->r_child,data);
	}
	return root;
}
 
TreeNode *createTree(void)
{
	int index = 0;
	TreeNode *root = NULL;
	root = insertNode(root,100);
	root = insertNode(root,50);
	root = insertNode(root,20);
	root = insertNode(root,80);
	root = insertNode(root,200);
	root = insertNode(root,150);
	root = insertNode(root,300);
	return root;
}

void printTree(TreeNode *root)
{
	if(root!=NULL)
	{
		printTree(root->l_child);
		cout<< root->data << " | ";
		printTree(root->r_child);
	}
}

void DFS(TreeNode *root)
{
	stack<TreeNode *> st;
	if(root == NULL)
	{
		return;
	}
	st.push(root);
	while(st.size()!=0)
	{ 
		TreeNode *tmp = st.top(); 
		st.pop();
		if(tmp->r_child != NULL)
		{
			st.push(tmp->r_child);	
		}
		if(tmp->l_child != NULL)
		{
			st.push(tmp->l_child);
		}
		cout<< tmp->data << " | ";
	}
}

void DFS_Recursive(TreeNode *root)
{
	if(root != NULL)
	{
		cout<< root->data << " | ";
		DFS_Recursive(root->l_child);	
		DFS_Recursive(root->r_child);
	}	
}

int main(int argc, char *argv[])
{
	TreeNode *root = createTree();
	printTree(root);
	
	cout<<endl;
	cout<< "without recursive" <<endl;
	DFS(root);

	cout<<endl;
	cout<< "recursive" <<endl;
	DFS_Recursive(root);
	return 0;
}

猜你喜欢

转载自www.cnblogs.com/achao123456/p/12242812.html