zoukankan      html  css  js  c++  java
  • 树的非递规遍历

    #include <iostream>
    #include <stack>
    
    using namespace std;
    
    struct Node{
    	int val;
    	Node* left;
    	Node* right;
    	Node(int x_) : val(x_), left(NULL), right(NULL){}
    };
    
    void InOrder(Node* root);
    void PostOrder(Node* root);
    void PreOrder(Node* root);
    
    void CreateTree(Node** root)
    {
    	int x;
    	Node *p;
    	if (*root == NULL){
    		cout << "plz input the root value(can't be 0): ";
    		cin >> x;
    		p = new Node(x);
    		(*root) = p;
    	}
    
    	cout << "input " << (*root)->val << "'s lchild(0 to end): ";
    	if (cin >> x && x != 0){
    		p = new Node(x);
    		(*root)->left = p;
    	}
    	cout << "input " << (*root)->val << "'s rchild(0 to end): ";
    	if (cin >> x && x != 0){
    		p = new Node(x);
    		(*root)->right = p;
    	}
    	if ((*root)->left)
    		CreateTree(&((*root)->left));
    	if ((*root)->right)
    		CreateTree(&((*root)->right));
    }
    
    
    int main()
    {
    	Node *root = NULL;
    	CreateTree(&root);
    	cout << "InOrder..." << endl;
    	InOrder(root);
    	cout << "
    PreOrder..." << endl;
    	PreOrder(root);
    	cout << "
    PostOrder..." << endl;
    	PostOrder(root);
    	return 0;
    }
    
    
    void InOrder(Node *root)
    {//为嘛我觉得这个很不好理解呢?
    	if (root == NULL) return;
    
    	stack<Node*> s;
    	Node *p = root;
    
    	while (p != NULL || !s.empty()){
    		while (p != NULL){
    			s.push(p);
    			p = p->left;
    		}
    		if (!s.empty()){
    			p = s.top();
    			cout << p->val << " ";
    			s.pop();
    			p = p->right;
    		}
    	}
    		
    }
    
    void PostOrder(Node* root)
    {
    	Node *p = root;
    	stack<Node*> s;
    	Node *visited;
    	
    	s.push(p);
    	while (!s.empty()){
    		p = s.top();
    		if ((p->left == NULL && p->right == NULL) || p->left == visited || p->right == visited){
    			cout << p->val << " ";
    			visited = p;
    			s.pop();
    		}else {
    			if (p->right && p->right != visited)
    				s.push(p->right);
    			if (p->left && p->left != visited)
    				s.push(p->left);
    		}
    	}
    }
    
    void PreOrder(Node* root)
    {
    	if (root == NULL) return;
    	stack<Node*> s;
    	Node* p = root;
    
    	while (p != NULL){
    		cout << p->val << " ";
    		if (p->right) s.push(p->right);
    		if (p->left)
    			p = p->left;
    		else if (!s.empty()){
    			p = s.top();
    			s.pop();
    		}else 
    			return;
    	}
    }
    
  • 相关阅读:
    Eclipse svn插件包
    最新版STS因为JDK版本太低无法启动的解决办法
    maven 项目无法发布,无法编译的解决办法
    maven依赖本地非repository中的jar包
    微信公众平台开发(2)-消息封装
    微信公众平台开发(4)-自定义菜单
    限制必须使用微信打开网页
    移动设备页面自适应
    微信公众平台开发(5)-上传下载多媒体文件
    微信公众平台开发(3)-回复消息
  • 原文地址:https://www.cnblogs.com/shamoof/p/4727175.html
Copyright © 2011-2022 走看看