二叉树的后续遍历

整理一份代码,之后要熟练掌握

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


//后序遍历非递归写法

class Solution {
public:
    vector postorderTraversal(TreeNode *root) {
        vector v;
        if(root == NULL) return v;
        stack s;
        s.push(root);
        TreeNode* temp = NULL;
        while(!s.empty()) {
            temp = s.top();
            if(temp->left == NULL && temp->right == NULL) {
                v.push_back(temp->val);
                s.pop();
            }else {
                if(temp->right) {
                    s.push(temp->right);
                    temp -> right = NULL;
                }
                if(temp->left) {
                    s.push(temp->left);
                    temp -> left = NULL;
                }
            }
        }
        return v;
    }
};
//特别要注意入栈顺序

你可能感兴趣的:(二叉树的后续遍历)