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?
非递归地遍历二叉树。坑爹...一开始用 if(!cur->left) 的形式来测试空指针...结果一直 runtime error....原来空指针的 bool 值不为 false 啊....
二叉树的前序和中序的非递归遍历比较好做,后序比较难想。不过思路还是用 stack 来解决的。我们需要思考一个问题,什么时候才可以访问一个元素(即遍历时处理到它)?
我们考虑对一个栈顶元素 cur ,如果:
C++:
/**
 * 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> ans;
        stack<TreeNode*> node;
        if(root == NULL) return ans;
        node.push(root);
        TreeNode* last = root;
        while(!node.empty())
        {
            TreeNode* cur = node.top();
            if(last == cur->right || last == cur->left || ((cur->right == NULL) && ( cur->left == NULL)))
            {
                ans.push_back(cur->val);
                node.pop();
                last = cur;
            } else {
                if(cur->right != NULL) node.push(cur->right);
                if(cur->left != NULL) node.push(cur->left);
            }
        }
        return ans;
    }
};
Python:
# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # @param root, a tree node
    # @return a list of integers
    def postorderTraversal(self, root):
        ans = []
        stack = []
        if root == None:
            return ans
        stack.append(root)
        last = root
        while len(stack):
            cur = stack[len(stack)-1]
            if last == cur.left or last == cur.right or (cur.left == None and cur.right == None):
                ans.append(stack.pop().val)
                last = cur
            else:
                if cur.right != None:
                    stack.append(cur.right)
                if cur.left != None:
                    stack.append(cur.left)
        return ans
【LeetCode】Binary Tree Postorder Traversal
原文地址:http://blog.csdn.net/jcjc918/article/details/44489363