【二叉树经典问题】145. Binary Tree Postorder Traversal

来源:互联网 发布:windows阻止软件自启 编辑:程序博客网 时间:2024/06/16 14:30

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?

解答:

/** * 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> res;        stack<TreeNode*> s;        if(!root)             return res;        s.push(root),s.push(root);//push twice        while(!s.empty()){            root=s.top();            s.pop();            if(!s.empty()&&root==s.top()){                if(root->right) s.push(root->right),s.push(root->right);//push twice                if(root->left) s.push(root->left),s.push(root->left);//push twice            }            else                res.push_back(root->val);        }        return res;    }};

其他解答(摘自Discuss):

第一种:

pre-order traversal is root-left-right, and post order is left-right-root. modify the code for pre-order to make it root-right-left, and thenreverse the output so that we can get left-right-root .

  1. Create an empty stack, Push root node to the stack.
  2. Do following while stack is not empty.

2.1. pop an item from the stack and print it.

2.2. push the left child of popped item to stack.

2.3. push the right child of popped item to stack.

  1. reverse the ouput.

    class Solution {public:    vector<int> postorderTraversal(TreeNode *root) {        stack<TreeNode*> nodeStack;        vector<int> result;        //base case        if(root==NULL)        return result;        nodeStack.push(root);    while(!nodeStack.empty())    {        TreeNode* node= nodeStack.top();          result.push_back(node->val);        nodeStack.pop();        if(node->left)        nodeStack.push(node->left);        if(node->right)        nodeStack.push(node->right);    }     reverse(result.begin(),result.end());     return result;    }

    };

第二种(Java写的):

public List<Integer> postorderTraversal(TreeNode root) {  List<Integer> res = new ArrayList<Integer>();    if (root == null)    return res;        Stack<TreeNode> s1 = new Stack<TreeNode>();  Stack<TreeNode> s2 = new Stack<TreeNode>();    s1.push(root);    while (!s1.isEmpty()) {    TreeNode node = s1.pop();    s2.push(node);        if (node.left != null)      s1.push(node.left);        if (node.right != null)      s1.push(node.right);  }    while (!s2.isEmpty())    res.add(s2.pop().val);    return res;}
第三种比较有代表性的就是之前博文里写的那个,用一个指针记录之前访问过的节点,当做标记。详见:http://blog.csdn.net/lishichengyan/article/details/77171343


原创粉丝点击