• [LeetCode]Binary Tree Postorder Traversal


    Given a binary tree, return the postorder traversal of its nodes' values.

    For example: Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [3,2,1].

    Note: Recursive solution is trivial, could you do it iteratively?

    思考:原思路是为每个节点增加一个标记。这个思路先序遍历不要标记,因为当前访问结点直接出栈,不用看是否访问过。不过此思路redefinition of 'struct TreeNode'。

    struct TreeNode {
    	int val;
    	TreeNode *left;
    	TreeNode *right;
    	bool flag;
    	TreeNode(int x) : val(x), left(NULL), right(NULL), flag(false) {}
    };
     
    class Solution {
    private:
    	vector<int> ret;
    public:
        vector<int> postorderTraversal(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
    		ret.clear();
    		if(!root) return ret;
    		stack<TreeNode *> s;
    		s.push(root);
    		while(!s.empty())
    		{
    			TreeNode *cur=s.top();
    			if(cur->left&&!cur->left->flag)
    				s.push(cur->left);
    			else if(cur->right&&!cur->right->flag) 
    				s.push(cur->right);
    			else
    			{
    				ret.push_back(cur->val);
    				cur->flag=true;
    				s.pop();
    			}
    		}
    		return ret;
        }
    };
    

           既然不能增加标记结点,那么遍历过的结点直接“删掉”。不过这么做破坏了原树结构。 

    class Solution {
    private:
    	vector<int> ret;
    public:
        vector<int> postorderTraversal(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
    		ret.clear();
    		if(!root) return ret;
    		stack<TreeNode *> s;
    		s.push(root);
    		TreeNode *cur=s.top();
    		while(!s.empty())
    		{
    			TreeNode *cur=s.top();
    			if(!cur->left&&!cur->right)
    			{
    				ret.push_back(cur->val);
    				s.pop();
    			}
    			if(cur->right)
    			{
    				s.push(cur->right);
    				cur->right=NULL;
    			}	
    			if(cur->left)
    			{
    				s.push(cur->left);
    				cur->left=NULL;
    			}	
    		}
    		return ret;
        }
    };
    

          网上搜索有没有更好的方法,发现自己思维定势了,只知道不能递归就用stack代替。参考http://www.cnblogs.com/changchengxiao/p/3416402.html

  • 相关阅读:
    [NOIP2006] 提高组 洛谷P1064 金明的预算方案
    [NOIP2006] 提高组 洛谷P1063 能量项链
    [NOIP2006] 提高组 洛谷P1065 作业调度方案
    [NOIP2005] 提高组 洛谷P1051 谁拿了最多奖学金
    [NOIP2005] 提高组 洛谷P1054 等价表达式
    [NOIP2005] 提高组 洛谷P1053 篝火晚会
    [NOIP2005] 普及组 循环
    Bzoj3622 已经没有什么好害怕的了
    [NOIP2006] 普及组
    Bzoj1008 [HNOI2008]越狱
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3425082.html
Copyright © 2020-2023  润新知