【leetcode】二叉樹後序遍歷(stack)

145. Binary Tree Postorder Traversal

leetcode題目

題目描述

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?

題解

左右根(left->right->root)。
用棧儲存遍歷得到結果序列。

Solution1:

/**
 * Definition for a binary tree node.
 * 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<const TreeNode* >s;
        /* 當前結點 */
        const TreeNode *cur = root;
        /* 記錄剛纔訪問的結點 */
        const TreeNode *just = nullptr;
        do {
            /* 向左下 */
            while ( cur != nullptr) {
                s.push(cur);
                cur = cur->left;
            }
            just = nullptr;
            while ( !s.empty()) {
                cur = s.top();
                s.pop();
                /* 右子樹不存在或已被訪問,訪問此結點 */
                if (cur->right == just) {
                    result.push_back(cur->val);
                    just = cur;
                } else {
                /* 當前節點不能訪問 */
                    s.push(cur);
                    /* 先到右子結點 */
                    cur = cur->right;
                    break;

                }
            }
        } while( !s.empty());
        return result;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章