[Leetcode][Tree][Binary Tree Postorder Traversal]

來源:互聯網
上載者:User

標籤:blog   os   for   leetcode   io   res   

二叉樹的後續遍曆

 

1、遞迴版本

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    void dfsPostorderTraversal(TreeNode *now, vector<int> &result) {        if (now == NULL) {            return;        }        dfsPostorderTraversal(now->left, result);        dfsPostorderTraversal(now->right, result);        result.push_back(now->val);    }    vector<int> postorderTraversal(TreeNode *root) {        vector<int> result;        dfsPostorderTraversal(root, result);        return result;    }};

  CE一次。。。為什麼我總是CE呢。。因為寫完之後覺得程式太簡單,所以不想檢查。。

2、迭代版本

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

後續遍曆需要兩個指標來選項組now和pre,還有3個迴圈的邊界,感覺這個程式可以寫成很多不同的版本。

關鍵是如何判斷now這個點的左子樹和右子樹都已經被訪問過了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.