LeetCode: Binary Tree Postorder Traversal

思路:非递归先序遍历二叉树算法,每次压栈时需要访问当前节点。

code:

class Solution {
public:
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> ret;
        if(root != NULL){
            stack<TreeNode *> s;
            TreeNode * p = root;
            s.push(p);
            ret.push_back(p->val);
            while(!s.empty()){
                while(p->left != NULL){
                    p = p->left;
                    ret.push_back(p->val);
                    s.push(p);
                }
                TreeNode * temp = s.top();
                s.pop();
                if(temp->right != NULL){
                    p = temp -> right;
                    ret.push_back(p->val);
                    s.push(p);
                }
            }
        }
        return ret;
    }
};


你可能感兴趣的:(LeetCode: Binary Tree Postorder Traversal)