LeetCode 145: Binary Tree Postorder Traversal

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?

解題思路

二叉樹後序遍歷的非遞歸算法,代碼如下:

/**
 * 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;

        if (root == NULL) return result;

        TreeNode *pre = NULL; // 指向上一次 “輸出” 的節點
        stack<TreeNode *> nodeStack;
        nodeStack.push(root);
        while (!nodeStack.empty()) {
            TreeNode *cur = nodeStack.top();

            if (((pre != NULL) && (cur->left == pre || cur->right == pre))
                            || (cur->left == NULL && cur->right == NULL)) {
                /* 如果當前節點爲葉節點,或者左右子樹均已經被訪問輸出,則直接輸出該節點,
                 * 將其出棧並將其設爲上一個訪問的節點 。
                 */
                nodeStack.pop();
                result.push_back(cur->val);
                pre = cur;
            }
            else {
                // 先入右子女,在入左子女
                if (cur->right != NULL) nodeStack.push(cur->right);
                if (cur->left != NULL) nodeStack.push(cur->left);
            }
        }

        return result;
    }
};
發佈了62 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章