zoukankan      html  css  js  c++  java
  • 二叉树的遍历算法

    二叉树的先序、中序、后序以及层次遍历算法

    非递归版本:

    vector<int> postorderTraversal(TreeNode *root){
    	vector<int> vect;
    	if (!root)
    	{
    		return vect;
    	}
    	stack<TreeNode*> stackData;
    	stackData.push(root);
    	TreeNode* cur = NULL;
    	TreeNode* pre = NULL;
    	while (!stackData.empty())
    	{
    		cur=stackData.top();
    		if (cur->left==NULL&&cur->right==NULL || (pre!=NULL)&&(pre==cur->left||pre==cur->right))
    		{
    			vect.push_back(cur->val);
    			pre=cur;
    			stackData.pop();
    		}else{
    			if (cur->right)
    			{
    				stackData.push(cur->right);
    			}
    
    			if (cur->left)
    			{
    				stackData.push(cur->left);
    			}
    		}
    	}
    	return vect;
    }
    
    
    vector<int> preordertTraversal(TreeNode *root){
    	
    	vector<int> vect;
    	
    	if (!root)
    	{
    		return vect;
    	}
    	stack<TreeNode*> stackData;
    	TreeNode *pNode = root;
    	while (pNode||!stackData.empty())
    	{
    		while (pNode)
    		{
    			vect.push_back(pNode->val);
    			stackData.push(pNode);
    			pNode=pNode->left;
    		}
    
    		if (!stackData.empty())
    		{
    			pNode=stackData.top();
    			stackData.pop();
    			pNode=pNode->right;
    		}
    	}
    
    	return vect;
    }
    
    vector<int> inorderTraversal(TreeNode *root){
    	vector<int> inorder;
    	stack<TreeNode*> stackData;
    	TreeNode *pNode=root;
    	while(pNode||!stackData.empty()){
    		while(pNode){
    			stackData.push(pNode);
    			pNode=pNode->left;
    		}
    
    		if(!stackData.empty()){
    			pNode=stackData.top();
    			inorder.push_back(pNode->val);
    			stackData.pop();
    			pNode = pNode->right;
    		}
    
    	}
    	return inorder;
    }
    
    vector<vector<int> > levelOrderBottom(TreeNode *root){
    	vector<vector<int> > result;
    	if (!root)
    	{
    		return result;
    	}
    	vector<int> curlevel;
    	queue<TreeNode*> q;
    	q.push(root);
    	q.push(NULL);
    	while (!q.empty())
    	{
    		TreeNode * node = q.front();
    		q.pop();
    
    		if(node)
    		{
    			curlevel.push_back(node->val);
    			if (node->left)
    			{
    				q.push(node->left);
    			}
    			if (node->right)
    			{
    				q.push(node->right);
    			}
    		}else {
    			result.push_back(curlevel);
    			curlevel.clear();
    			if(!q.empty())  //该处相当关键 否则会出现死循环
    				q.push(NULL);
    		}
    	}
    	reverse(result.begin(),result.end());
    	return result;  
    }
    

      

  • 相关阅读:
    工作所得所思之一
    angular路由
    html中offsetTop、clientTop、scrollTop、offsetTop各属性介绍
    您无权输入许可证密钥,请请使用系统管理员账户重试
    nginx的配置说明
    flexbox弹性盒子模型
    移动web开发规范
    为什么要使用响应式开发
    移动web开发
    如何给图片做缓存
  • 原文地址:https://www.cnblogs.com/liwenzhu/p/4000896.html
Copyright © 2011-2022 走看看