zoukankan      html  css  js  c++  java
  • 二叉树的深度优先遍历(递归和非递归方式)

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

    #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;
    }
  • 相关阅读:
    应用程序池的配置 狼
    SQL跨数据库复制表数据 狼
    <script language= "javascript " for= "window " event= "onload "> 狼
    禁止虚拟目录继承根目录下web.config中的有些配置 web.config的继承禁止方法 狼
    linux 在程序里修改系统时间
    xlinux下载地址
    安装tslib1.4出现的问题汇总
    linux之看门狗 (转)
    VC中显示GIF图片
    mdev 自动挂载U盘成功
  • 原文地址:https://www.cnblogs.com/achao123456/p/12242812.html
Copyright © 2011-2022 走看看