zoukankan      html  css  js  c++  java
  • 145. Binary Tree Postorder Traversal

    • 后序遍历二叉树(非递归实现)
      题目来源

    • C++代码实现

    class Solution
    {
    public:
    	vector<int> postorderTraversal(TreeNode* root)
    	{
    		vector<int> result;
    		stack<TreeNode*> datastack1;
    		stack<TreeNode*> datastack2;
    
    		if (root != NULL)
    		{
    			datastack1.push(root);
    
    			while (!datastack1.empty())
    			{
    				root = datastack1.top();
    				datastack2.push(root);
    				datastack1.pop();
    				if (root->left != NULL)
    				{
    					datastack1.push(root->left);
    				}
    				if (root->right != NULL)
    				{
    					datastack1.push(root->right);
    				}
    			}
    		}
    		int length = datastack2.size();
    		for (int i = 0; i < length; i++)
    		{
    			result.push_back((datastack2.top())->val);
    			datastack2.pop();
    		}
    
    		return result;
    	}
    };
    

    将最后的datastack2result中倒数据改为如下代码也可:

            while(!datastack2.empty())
            {
                result.push_back( (datastack2.top() )->val);
                datastack2.pop();
            }
    		
    
    • 第一次出现BUG:
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution 
    {
    public:
        vector<int> postorderTraversal(TreeNode* root)
    	{
    		vector<int> result;
            stack<TreeNode*> datastack1;
    		stack<TreeNode*> datastack2;
    		
            if(root != NULL)
    		{
    			datastack1.push(root);
    			
    			while(!datastack1.empty())
    			{
    				root = datastack1.top();
    				datastack2.push(root);
    				datastack1.pop();
    				if(root->left != NULL)
    				{
    					datastack1.push(root->left);
    				}
    				if(root->right != NULL)
    				{
    					datastack1.push(root->right);
    				}
    			}
    		}
    		
    		for(int i = 0;i < datastack2.size();i++)
    		{
    			result.push_back( (datastack2.top() )->val);
    			datastack2.pop();
    		}
    		
    		return result;
        }
    };
    

    最后发现BUG出现在

    		for(int i = 0;i < datastack2.size();i++)
    		{
    			result.push_back( (datastack2.top() )->val);
    			datastack2.pop();
    		}
    

    datastack2每pop出一次数据,datastack2.size()就会减一,同时i++,导致过早的结束了这个循环,正确的写法如下:

    		int length = datastack2.size();
    		for (int i = 0; i < length; i++)
    		{
    			result.push_back((datastack2.top())->val);
    			datastack2.pop();
    		}
    
  • 相关阅读:
    「考试」省选27
    「考试」省选26
    「考试」省选25
    $dy$讲课总结
    「笔记」$Min\_25$筛
    「考试」省选24
    「总结」多项式生成函数例题(4)
    「总结」多项式生成函数相关(4)
    「考试」省选23
    「总结」后缀3
  • 原文地址:https://www.cnblogs.com/Manual-Linux/p/12076160.html
Copyright © 2011-2022 走看看