Leetcode: Binary Tree Postorder Traversal - 再解

前几天做过,很混乱 http://blog.csdn.net/u013166464/article/details/17455723。

跟前序,中序一块考虑,简单些的解法:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 #include <stack>
 #include <vector>
 
class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> result;
        stack<TreeNode*> stack_tree;
        TreeNode *prev = NULL;
        while (root != NULL || !stack_tree.empty()) {
            while (root != NULL) {
                stack_tree.push(root);
                root = root->left;
            }
            if (!stack_tree.empty()) {
                root = stack_tree.top();
                if (root->right == NULL || root->right == prev) {
                    result.push_back(root->val);
                    prev = root;
                    root = NULL;
                    stack_tree.pop();
                }
                else {
                    root = root->right;
                }
            }
        }
        
        return result;
    }
};

=========================第二次============================

标准解法。非递归很重要,不少面试题的变种。

/**
 * 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;
        stack<TreeNode*> nodes;
        TreeNode *prev = NULL;
        while (root != NULL || !nodes.empty()) {
            while (root != NULL) {
                nodes.push(root);
                root = root->left;
            }
            
            if (!nodes.empty()) {
                root = nodes.top();
                if (root->right == NULL || root->right == prev) {
                    result.push_back(root->val);
                    nodes.pop();
                    prev = root;
                    root = NULL;
                }
                else {
                    root = root->right;
                }
            }
        }
        
        return result;
    }
};


你可能感兴趣的:(LeetCode,二叉树,遍历)