[LeetCode]Binary Tree Postorder Traversal,leetcodepostorder

來源:互聯網
上載者:User

[LeetCode]Binary Tree Postorder Traversal,leetcodepostorder
【題目】

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?
【代碼】

/**********************************   日期:2014-12-07*   作者:SJF0115*   題號: Binary Tree Postorder Traversal*   來源:https://oj.leetcode.com/problems/binary-tree-postorder-traversal/*   結果:AC*   來源:LeetCode*   總結:**********************************/#include <iostream>#include <malloc.h>#include <vector>#include <stack>using namespace std;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> v;        stack<TreeNode *> stack;        TreeNode *p = root;        TreeNode *q;        do{            //遍曆左子樹            while(p != NULL){                stack.push(p);                p = p->left;            }            q = NULL;            while(!stack.empty()){                p = stack.top();                stack.pop();                // 右子樹是否為空白或者已訪問過                if(p->right == q){                    v.push_back(p->val);                    //保留訪問過的節點                    q = p;                }                else{                    //當前節點不能訪問,p節點重新入棧                    stack.push(p);                    //處理右子樹                    p = p->right;                    break;                }//if            }//while        }while(!stack.empty());//while        return v;    }};//按先序序列建立二叉樹int CreateBTree(TreeNode* &T){    char data;    //按先序次序輸入二叉樹中結點的值(一個字元),‘#’表示空樹    cin>>data;    if(data == '#'){        T = NULL;    }    else{        T = (TreeNode*)malloc(sizeof(TreeNode));        //產生根結點        T->val = data-'0';        //構造左子樹        CreateBTree(T->left);        //構造右子樹        CreateBTree(T->right);    }    return 0;}int main() {    Solution solution;    TreeNode* root(0);    CreateBTree(root);    vector<int> v = solution.postorderTraversal(root);    for(int i = 0;i < v.size();i++){        cout<<v[i]<<endl;    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.