码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Binary Tree Postorder Traversal

时间:2014-12-07 17:49:21      阅读:135      评论:0      收藏:0      [点我收藏+]

标签: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?

【代码】

/*********************************
*   日期: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;
    }
}


[LeetCode]Binary Tree Postorder Traversal

标签:leetcode   二叉树   

原文地址:http://blog.csdn.net/sunnyyoona/article/details/41788775

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!