首页 > 代码库 > 【Leetcode】Binary Tree Postorder Traversal

【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?

思路:后序遍历比起先序遍历以及中序遍历要稍微复杂一点,可以考虑用两个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;
	}
};