码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Postorder Traversal

时间:2014-12-20 19:36:13      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

先简单介绍下先序遍历、中序遍历和后序遍历,

技术分享

先序遍历为ABC,中序遍历为BAC,后续遍历为BCA,根节点在的位置决定了什么遍历。

该题的递归解法:

class Solution {
public:
	typedef TreeNode * STreeNode;
	vector<int> buf;
    vector<int> postorderTraversal(TreeNode *root) {

         if(root != NULL)
         rpostorder(root);

		 return buf;
   
    }
	void rpostorder(TreeNode *root)
    {
     	if(root->left == NULL && root->right == NULL)
        {
           buf.push_back(root->val);
		   return ;
		}

		if(root->left != NULL)
		{
		   rpostorder(root->left);
           
		}
		if(root->right != NULL)
		{
		   rpostorder(root->right);
		}
		buf.push_back(root->val);

	}
	
};

 该题的非递归解法:

class Solution {
public:
	typedef TreeNode * STreeNode;
	vector<int> result;
    vector<int> postorderTraversal(TreeNode *root) {
         stack<pair<STreeNode,bool>> buf; 
         if(root == NULL)
		 return result;
		 while(1)
		 {

	        if(root->left == NULL && root->right == NULL)
	        {
	           result.push_back(root->val);
			   root = GetData(buf);
			   if(root == NULL)
			   break;
			}
            else if(root->left != NULL)
			{
			  
			   buf.push(pair<STreeNode,bool>(root,true));
			   if(root->right != NULL)
			   {
			      buf.push(pair<STreeNode,bool>(root->right,false));
			   }
			   root = root->left;  
			}
			else 
			{
              
			   buf.push(pair<STreeNode,bool>(root,true));
			   root = root->right;  
			}
			
		}
     

		 return result;
   
    }
	STreeNode GetData(stack<pair<STreeNode,bool>> &buf)
	{
	    pair<STreeNode,bool> temp;
		if(buf.size() == 0)
		return NULL;
    	
		while(1)
		{
		    temp = buf.top();
		    buf.pop();
			if(temp.second == false)
				break;
            result.push_back((temp.first)->val);
		  
		    if(buf.size() == 0)
		    	break;
		}
        if(temp.second == true)
		return NULL;
		else
		return temp.first;

	}
	
};

 

Binary Tree Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/xgcode/p/4175706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!