1. 程式人生 > >leetcode 145.Binary Tree Postorder Traversal

leetcode 145.Binary Tree Postorder Traversal

leetcode 145. Binary Tree Postorder Traversal

題目:

Given a binary tree, return the postorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [3,2,1]

Follow up: Recursive solution is trivial, could you do it iteratively?


解法:

這個題就是讓我們實現二叉樹的後序遍歷,可以用遞迴的方式也可以用非遞迴的方式,由於非遞迴只有幾行程式碼,比較簡單,這裡主要是需要了解一下非遞迴的方式。

非遞迴的後序遍歷主要是用到了資料結構來儲存最下層的結點,通過每一次一個一個結點的彈出,從最下層來訪問對應的元素。


程式碼:

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        if (!root) return {};
        vector<int> res;
        stack<TreeNode*> s{{root}};
        TreeNode *head = root;
        while
(!s.empty()) { TreeNode *t = s.top(); if ((!t->left && !t->right) || t->left == head || t->right == head) { res.push_back(t->val); s.pop(); head = t; } else { if (t->right) s.
push(t->right); if (t->left) s.push(t->left); } } return res; } };