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

【Leetcode】Binary Tree Postorder Traversal

时间:2014-06-15 19:06:52      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   http   

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?

思路:后序遍历比起先序遍历以及中序遍历要稍微复杂一点,可以考虑用两个stack进行操作,一个用于存储遍历的元素,一个用于存储打印顺序。

代码一:

/**
 * Definition for binary tree
 * 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;
        
        if(root == NULL)
            return result;
            
        stack<TreeNode *> trialStack;
        stack<TreeNode *> outputStack;
        
        TreeNode *node = root;
        trialStack.push(node);
        
        while(!trialStack.empty())
        {
            TreeNode *temp = trialStack.top();
            trialStack.pop();
            outputStack.push(temp);
            
            if(temp->left != NULL)
                trialStack.push(temp->left);
                
            if(temp->right != NULL)
                trialStack.push(temp->right);
        }
        
        while(!outputStack.empty())
        {
            TreeNode *temp = outputStack.top();
            outputStack.pop();
            
            result.push_back(temp->val);
        }
        
        return result;
    }
};

代码二:

使用一个标记位进行标记,所需空间有所降低。代码来自https://github.com/soulmachine/leetcode

// 使用栈,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
	vector<int> postorderTraversal(TreeNode *root) {
		vector<int> result;
		/* p,正在访问的结点,q,刚刚访问过的结点*/
		const TreeNode *p, *q;
		stack<const TreeNode *> s;
		p = root;
		do {
			while (p != nullptr) { /* 往左下走*/
				s.push(p);
				p = p->left;
			}
			q = nullptr;
			while (!s.empty()) {
				p = s.top();
				s.pop();
				/* 右孩子不存在或已被访问,访问之*/
				if (p->right == q) {
					result.push_back(p->val);
					q = p; /* 保存刚访问过的结点*/
				} else {
					/* 当前结点不能访问,需第二次进栈*/
					s.push(p);
					/* 先处理右子树*/
					p = p->right;
					break;
				}
			}
		} while (!s.empty());
		return result;
	}
};



【Leetcode】Binary Tree Postorder Traversal,布布扣,bubuko.com

【Leetcode】Binary Tree Postorder Traversal

标签:des   style   class   blog   code   http   

原文地址:http://blog.csdn.net/lipantechblog/article/details/30368649

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