Binary Tree Postorder Traversal

来源:互联网 发布:ios远程访问mac 编辑:程序博客网 时间:2024/06/05 05:46

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?

后序遍历,不能使用递归

class Solution {public:    vector<int> postorderTraversal(TreeNode *root) {        vector<int> rel;        if(root==NULL) return rel;        s.push(*root);        while(!s.empty()) {            TreeNode  & v = s.top();            if(v.right==NULL && v.left==NULL) {                rel.push_back(v.val);                s.pop();            } else {                if(v.right!=NULL) {                    s.push(*v.right);                    v.right = NULL;                }                if(v.left!=NULL) {                    s.push(*v.left);                    v.left = NULL;                };            }        }        return rel;    }    stack<TreeNode> s;};


0 0
原创粉丝点击