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

[LeetCode] Binary Tree Postorder Traversal

时间:2015-04-05 16:04:34      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode      

Binary Tree Postorder Traversal

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?

解题思路:

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:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> result;
        postOrder(root, result);
        return result;
    }
    
    void postOrder(TreeNode *node, vector<int>& result){
        if(node==NULL){
            return;
        }
        postOrder(node->left, result);
        postOrder(node->right, result);
        result.push_back(node->val);
    }
};


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;
        
        stack<TreeNode*> s;         //最终结果栈
        stack<TreeNode*> sLeftNode; //左孩子栈
        TreeNode* node=root;
        
        while(node!=NULL||!sLeftNode.empty()){
            if(node!=NULL){
                s.push(node);
                if(node->left!=NULL){
                    sLeftNode.push(node->left);
                }
                node=node->right;
            }else{
                node=sLeftNode.top();
                sLeftNode.pop();
            }
        }
        while(!s.empty()){
            node=s.top();
            result.push_back(node->val);
            s.pop();
        }
        
        return result;
    }
};



[LeetCode] Binary Tree Postorder Traversal

标签:c++   leetcode      

原文地址:http://blog.csdn.net/kangrydotnet/article/details/44887859

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