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

Binary Tree Postorder Traversal

时间:2017-04-02 11:04:29      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:tree node   null   logs   result   ret   版本   return   使用   指针   

思路一:递归版本

/**
 * 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 == nullptr)
            return result;
        
        postorder(root, result);
        return result;
    }
    
    void postorder(TreeNode *cur, vector<int> &result)
    {
        if(cur->left != nullptr)
            postorder(cur->left, result);
        if(cur->right != nullptr)
            postorder(cur->right, result);
        result.push_back(cur->val);
    }
};

思路二:非递归版本,前序遍历中使用了一个额外的指针,这里使用times记录节点出栈的次数,更加方便直观

/**
 * 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 {
private:
    struct Node{
        TreeNode *node;
        int times;
        
        Node(TreeNode *tmp=nullptr):node(tmp), times(0){}
    };

public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> result;
        if(root == nullptr)
            return result;
        stack<Node> s;
    
        Node current(root);
        s.push(current);
        
        while(!s.empty())
        {
            current = s.top();
            
            if(current.times == 0)
            {
                 ++s.top().times;
                if(current.node->left != nullptr)
                    s.push(Node(current.node->left));
            }
            else if(current.times == 1)
            {
                 ++s.top().times;
                if(current.node->right != nullptr)
                    s.push(Node(current.node->right));
            }
            else
            {
                result.push_back(current.node->val);
                cout<<"hi"<<endl;
                s.pop();
            }
        }

        return result;
    }
};

 

Binary Tree Postorder Traversal

标签:tree node   null   logs   result   ret   版本   return   使用   指针   

原文地址:http://www.cnblogs.com/chengyuz/p/6657524.html

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